3

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.

Tanuki
  • 717
  • 1
  • 9
  • 24

2 Answers2

3

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);
Community
  • 1
  • 1
jjj
  • 4,822
  • 1
  • 16
  • 39
1

Add this:

modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256)); 
ranquild
  • 1,799
  • 1
  • 16
  • 25