Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
    }
}
like image 477
Vinicius Rocha Avatar asked Jun 14 '14 16:06

Vinicius Rocha


People also ask

What is OnModelCreating method?

The DbContext class has a method called OnModelCreating that takes an instance of ModelBuilder as a parameter. This method is called by the framework when your context is first created to build the model and its mappings in memory.

What is IEntityTypeConfiguration?

IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).

What is ModelBuilder in Entity Framework?

The ModelBuilder is the class which is responsible for building the Model. The ModelBuilder builds the initial model from the entity classes that have DbSet Property in the context class, that we derive from the DbContext class. It then uses the conventions to create primary keys, Foreign keys, relationships etc.

What is fluent API configuration?

Fluent API is an advanced way of specifying model configuration that covers everything that data annotations can do in addition to some more advanced configuration not possible with data annotations.


2 Answers

Simpler Answer

modelBuilder.Configurations.AddFromAssembly(GetType().Assembly);
like image 29
oddmike Avatar answered Oct 21 '22 20:10

oddmike


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

modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);
like image 148
mr100 Avatar answered Oct 21 '22 21:10

mr100