EF Core Fluent Api链接配置

时间:2018-03-09 13:12:15

标签: entity-framework ef-fluent-api

如何在EF Core Fluent API中进行链接,而不是逐行重复表格的每个属性:

        builder.Entity<FoodWeight>().HasIndex(x => x.NutrientDatabankNumber);
        builder.Entity<FoodWeight>().Property(x => x.NutrientDatabankNumber).HasColumnName("NDB_No");
        builder.Entity<FoodWeight>().Property(x => x.SequenceNumber).HasColumnName("Seq");
        builder.Entity<FoodWeight>().Property(x => x.Amount).HasColumnName("Amount");
        builder.Entity<FoodWeight>().Property(x => x.Description).HasColumnName("Msre_Desc");
        builder.Entity<FoodWeight>().Property(x => x.GramWeight).HasColumnName("Gm_Wgt");
        builder.Entity<FoodWeight>().Property(x => x.GramWeight).HasColumnName("Gm_Wgt");
        builder.Entity<FoodWeight>().Property(x => x.NumberOfDataPoints).HasColumnName("Num_Data_Pts");
        builder.Entity<FoodWeight>().Property(x => x.StandardDeviation).HasColumnName("Std_Dev");

1 个答案:

答案 0 :(得分:0)

您总是可以向EntityTypeBuilder添加扩展方法,但这并不会大大降低冗长程度:


modelBuilder
    .Entity<FoodWeight>()
    .Configure(
        entity => entity.HasIndex(x => x.NutrientDatabankNumber),
        entity => entity.Property(x => x.NutrientDatabankNumber).HasColumnName("NDB_No"),
        entity => entity.Property(x => x.SequenceNumber).HasColumnName("Seq")
    );

扩展方法:

public static class EntityTypeBuilderExtensions
{
    public static void Configure<T>(this EntityTypeBuilder<T> modelBuilder, params Action<EntityTypeBuilder<T>>[] builders) where T : class
    {
        builders
            .ToList()
            .ForEach(builder => builder(modelBuilder));
    }
}