C# 如何在实体框架fluent api中设置所有字段的默认长度?
是否可以设置所有字符串字段的默认长度(除非我另有说明)? 现在,我真的很讨厌去添加这样的东西C# 如何在实体框架fluent api中设置所有字段的默认长度?,c#,.net,entity-framework,ef-fluent-api,C#,.net,Entity Framework,Ef Fluent Api,是否可以设置所有字符串字段的默认长度(除非我另有说明)? 现在,我真的很讨厌去添加这样的东西 modelBuilder.Entity().Property(x=>x.YardLine).HasMaxLength(256) 添加到每个字符串字段,只是为了避免数据库中所有“我的字符串”列上都有nvarchar(max)。添加以下内容: modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256)); m
modelBuilder.Entity().Property(x=>x.YardLine).HasMaxLength(256)代码>
添加到每个字符串字段,只是为了避免数据库中所有“我的字符串”列上都有nvarchar(max)。添加以下内容:
modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256));
modelBuilder.Properties().Configure(p=>p.HasMaxLength(256));
您可以使用名为的东西,但前提是您使用的是Entity Framework 6+
作为@ranquild,您可以使用
modelBuilder.Properties<string>().Configure(p => p.HasMaxLength(256));
modelBuilder.Properties().Configure(p=>p.HasMaxLength(256));
为所有字符串属性配置默认最大长度。您甚至可以筛选要应用配置的属性:
modelBuilder.Properties<string>()
.Where(p => someCondition)
.Configure(p => p.HasMaxLength(256));
modelBuilder.Properties()
.其中(p=>someCondition)
.Configure(p=>p.HasMaxLength(256));
最后,实体类型本身的任何配置都将优先。例如:
modelBuilder.Entity<EntityType>().Property(x => x.StringProperty)
.HasMaxLength(DifferentMaxLength);
modelBuilder.Entity().Property(x=>x.StringProperty)
.最大长度(不同的最大长度);