I have a hierarchy and I want to configure it in one class. Is it possible?
Currently I have N
implementations for IEntityTypeConfiguration<>
interface - one per each entity in the hierarchy.
I have a hierarchy and I want to configure it in one class. Is it possible?
Currently I have N
implementations for IEntityTypeConfiguration<>
interface - one per each entity in the hierarchy.
Sure it is possible. After all, you are not forced to use IEntityTypeConfiguration<>
at all - you can configure all your entities inside OnModelCreating
. Also all the ApplyConfiguration
generic method does is to call Configure
method of the class implementing the IEntityTypeConfiguration<TEntity>
interface passing EntityTypeBuilder<TEntity>
instance which you normally get from modelBuilder.Entity<TEntity>()
call (or receive as an argument of the Action<>
of the second overload of that method).
Hence you can put your code in any static or instance class method receiving the ModelBuilder
instance. If you want to use class, it shouldn't implement IEntityTypeConfiguration<>
because there is no way to get ModelBuilder
from ``EntityTypeBuilder`, and you need it in order to be able to configure both base and derived entities.
For instance, something like this:
class MyHierarchyConfiguration
{
public void Apply(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyBaseEntity>(builder =>
{
// base entity configuration here
});
modelBuilder.Entity<MyDerivedEntity1>(builder =>
{
// derived entity configuration here
});
modelBuilder.Entity<MyDerivedEntity2>(builder =>
{
// derived entity configuration here
});
// etc.
}
}
and inside OnModelCreating
:
new MyHierarchyConfiguration().Apply(modelBuilder);