This is a feature request.
In EF6 there was a method to add all model configurations from assembly. It was very convenient, as developer does not need to explicitly add model configurations.
Are you planning to implement it? Is it OK to have it?
I have implemented it with this code:
```C#
protected void ConfigureAllEntityTypes(ModelBuilder modelBuilder)
{
var applyConfigMethod = typeof(ModelBuilder).GetMethods()
.Where(e => e.Name == "ApplyConfiguration"
&& e.GetParameters().Single().ParameterType.Name == typeof(IEntityTypeConfiguration<>).Name)
.Single();
foreach (var item in GetAllImplementingIEntityTypeConfiguration())
{
var entityType = item.ImplementedInterfaces.Single().GenericTypeArguments.Single();
var applyConfigGenericMethod = applyConfigMethod.MakeGenericMethod(entityType);
applyConfigGenericMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(item) });
}
}
protected List
{
return Assembly.GetExecutingAssembly().DefinedTypes
.Where(t => t.ImplementedInterfaces
.Any(i =>
i.IsGenericType
&& i.Name == typeof(IEntityTypeConfiguration<>).Name)
&& t.IsClass
&& !t.IsAbstract
&& !t.IsNested)
.ToList();
}
```
Is this OK for production use? Is there a simpler way to make it work?
@kmolerov We are not planning to add this functionality to EF Core. Scanning assemblies can be fine for some cases, but it gets hard to do reliably across all platforms and can be a source of obscure bugs.
I don't think that this is a legitimate reason to not add similar functionality. Imagine you have a project with 150 entities and constantly adding more. Every time you have to add a configuration you also have to add it in model builder. This is a repetitive work, which leads to team members forgetting to add configurations.
I know it that 150 entities in same DbContext is too much, so we have to think about a way how to automatically add them in different contexts. Maybe it will be easier to set context directly inside IEntityTypeConfiguration Configure method.
@kmolerov and @ajcvickers If EF Core team have no plan to implement this feature then this is the solution that I am using which is much better than assigning one by one.
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var typesToRegister = Assembly.GetExecutingAssembly().GetTypes()
.Where(t => t.GetInterfaces().Any(gi => gi.IsGenericType && gi.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))).ToList();
foreach (var type in typesToRegister)
{
dynamic configurationInstance = Activator.CreateInstance(type);
modelBuilder.ApplyConfiguration(configurationInstance);
}
}
Most helpful comment
@kmolerov and @ajcvickers If EF Core team have no plan to implement this feature then this is the solution that I am using which is much better than assigning one by one.