Home > Mobile >  Entity Framework Core modelBuilder.ApplyConfigurationsFromAssembly scan all Configuration
Entity Framework Core modelBuilder.ApplyConfigurationsFromAssembly scan all Configuration

Time:01-07

Refer: modelBuilder.Configurations.AddFromAssembly in EF Core

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   base.OnModelCreating(modelBuilder);

   modelBuilder.ApplyConfigurationsFromAssembly(typeof(UserConfiguration).Assembly); // Here UseConfiguration is any IEntityTypeConfiguration
}

I've taken the above from the StackOverflow URL above.

In my OnModelCreating, I have multiple ApplyConfigurationsFromAssembly, one line for each Configuration.

1. modelBuilder.ApplyConfigurationsFromAssembly(typeof(CustomerConfiguration).Assembly); 
2. modelBuilder.ApplyConfigurationsFromAssembly(typeof(OrderConfiguration).Assembly); 
3. modelBuilder.ApplyConfigurationsFromAssembly(typeof(ProductConfiguration).Assembly); 

When I was doing a debug, what I notice is that when executing line 1, the program does not only execute CustomerConfiguration. It also execute the other Configuration. This is the same when executing line 2 and line 3.

I also notice that there are some Configuration which were in the same folder but was not mentioned in OnModelCreating, they were also executed.

  1. Is this the correct way to code the program if I have a number of Configurations ?
  2. If yes, how does EF know about the other Configuration and scan it ?
  3. Should I just have 1 ApplyConfiguration ? If yes, how do I decided which one to mention ?

Thanks.

CodePudding user response:

ModelBuilder.ApplyConfigurationsFromAssembly as clear from the name will apply all configurations from the passed assembly:

Applies configuration from all IEntityTypeConfiguration<TEntity> instances that are defined in provided assembly.

So it seems that CustomerConfiguration, OrderConfiguration and ProductConfiguration are in the same assembly (project).

If yes, how does EF know about the other Configuration and scan it ?

You are passing an assembly, EF will use reflection to process it and find all classes implementing IEntityTypeConfiguration<TEntity>.

Should I just have 1 ApplyConfiguration ? If yes, how do I decided which one to mention ?

Yes. One per assembly containing your entity configurations (usually they are store in one). You can use any type from this assembly, not just the configuration ones.

Read more:

  • Related