如何添加所有EntityTypeConfiguration<>从当前组装自动?

时间:2014-06-14 16:28:31

标签: c# entity-framework reflection

如何添加所有EntityTypeConfiguration<>从当前的装配自动?

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 个答案:

答案 0 :(得分:33)

这应该很容易,因为DbModelBuilder提供了特殊的方法。尝试在OnModelCreating方法中添加此内容:

modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);

答案 1 :(得分:11)

更简单的答案

modelBuilder.Configurations.AddFromAssembly(GetType().Assembly);