How do I add all EntityTypeConfiguration<> from

2019-04-06 06:13发布

How do I add all EntityTypeConfiguration<> from current assembly automatically?

public class Entities : DbContext
{
    public Entities()
        : base("Entities")
    {
    }

    public virtual DbSet<User> Users { get; set; }

    // ...

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

        foreach(var configuration in this.GetAllConfigurations())
        {
            modelBuilder.Configurations.Add(configuration);
        }
    }

    private ... GetAllConfigurations()
    {
        // TODO: Get all configurations from current ASSEMBLY
    }
}

2条回答
Juvenile、少年°
2楼-- · 2019-04-06 06:39

It should be very easy as DbModelBuilder offers special method for that. Try add this within OnModelCreating method:

modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);
查看更多
倾城 Initia
3楼-- · 2019-04-06 06:46

Simpler Answer

modelBuilder.Configurations.AddFromAssembly(GetType().Assembly);
查看更多
登录 后发表回答