简体   繁体   中英

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

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.

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);

添加:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM