How to set default length on all fields in entity framework fluent api?

4k views Asked by At

Is it possible to set default length of all string fields (unless I say otherwise)? At the moment it really bugs me to go and add something like

modelBuilder.Entity<Game>().Property(x => x.YardLine).HasMaxLength(256); to each and every string field, just to avoid having nvarchar(max) on all my strings columns in the database.

2

There are 2 answers

0
jjj On BEST ANSWER

You can use something called Custom Code First Conventions, but only if you're using Entity Framework 6+.

As @ranquild mentions, you can use

modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256));

to configure the default maximum length for all string properties. You can even filter which properties to apply your configuration to:

modelBuilder.Properties<string>()
    .Where(p => someCondition)
    .Configure(p => p.HasMaxLength(256));

Finally, any configuration on the entity type itself would take precedence. For example:

modelBuilder.Entity<EntityType>().Property(x => x.StringProperty)
    .HasMaxLength(DifferentMaxLength);
0
Alexander Polyankin On

Add this:

modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256));