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
}
}
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.
IEntityTypeConfiguration<TEntity> InterfaceAllows configuration for an entity type to be factored into a separate class, rather than in-line in OnModelCreating(ModelBuilder).
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.
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.
Simpler Answer
modelBuilder.Configurations.AddFromAssembly(GetType().Assembly);
It should be very easy as DbModelBuilder
offers special method for that. Try add this within OnModelCreating
method:
modelBuilder.Configurations.AddFromAssembly(typeof(MyDbContext).Assembly);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With