简体   繁体   English

如何在实体框架流利的api中的所有字段上设置默认长度?

[英]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. 到每个字符串字段,只是为了避免在数据库中所有我的字符串列上使用nvarchar(max)。

You can use something called Custom Code First Conventions , but only if you're using Entity Framework 6+. 您可以使用“ 自定义代码优先约定” ,但前提是您使用的是Entity Framework 6+。

As @ranquild mentions , you can use 作为@ranquild 提到 ,您可以使用

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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