首先是实体框架代码中所有属性的必需规则

DiP*_*Pix 1 c# entity-framework ef-code-first asp.net-core

我首先使用代码和Entity Framework Core中的流畅API来确定属性的行为。

我想知道是否有任何方法可以替换这部分。

 modelBuilder.Entity<Person>()
            .Property(b => b.Name)
            .IsRequired();

 modelBuilder.Entity<Person>()
            .Property(b => b.LastName)
            .IsRequired();

 modelBuilder.Entity<Person>()
            .Property(b => b.Age)
            .IsRequired();
Run Code Online (Sandbox Code Playgroud)

用这样的东西:

 modelBuilder.Entity<Person>()
            .AllProperties()
            .IsRequired();
Run Code Online (Sandbox Code Playgroud)

关键是有时大多数属性甚至所有属性都必须为非空。并且标记每个属性并不优雅。

Oma*_*llo 5

一个解决方案可能是使用反射:

var properties = typeof(Class).GetProperties();

foreach (var prop in properties)
{
    modelBuilder.Entity<Class>().Property(prop.PropertyType, prop.Name).IsRequired();
}
Run Code Online (Sandbox Code Playgroud)

请注意,所有属性都将根据需要进行设置。当然,您可以根据类型(例如)过滤要根据需要设置的属性。

更新

使用扩展方法可以使其更加整洁。

EntityTypeBuilderExtensions.cs

public static class EntityTypeBuilderExtensions
{
    public static List<PropertyBuilder> AllProperties<T>(this EntityTypeBuilder<T> builder, Func<PropertyInfo, bool> filter = null) where T : class
    {
        var properties = typeof(T).GetProperties().AsEnumerable();

        if (filter != null) properties = properties.Where(x => filter(x));

        return properties.Select(x => builder.Property(x.PropertyType, x.Name)).ToList();
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的用途DbContext

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Class>().AllProperties().ForEach(x => x.IsRequired());
}
Run Code Online (Sandbox Code Playgroud)

如果您只想将IsRequired某类的特定属性应用到您,则可以将过滤器函数传递给该AllProperties方法。

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    //Required is applied only for string properties
    modelBuilder.Entity<Class>().AllProperties(x => x.PropertyType == typeof(string)).ForEach(x => x.IsRequired());
}
Run Code Online (Sandbox Code Playgroud)