Mass Register IEntityTypeConfiguration <> Entity Framework core

Ok, so I am using an entity infrastructure with a kernel and a clean core and first code porting. This is not a problem as such, I just wondered if anyone had found a better way to do this.

I currently have many object type configurations such as

public class ExampleEntityConfiguration : IEntityTypeConfiguration<ExampleEntity>
{
   public void Configure(EntityTypeBuilder<ExampleEntity> builder)
   {
      builder.Property(p => p.Id).ValueGeneratedNever();

      // more options here
   }
}

and I will register them in my dbcontext so

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

  modelBuilder.ApplyConfiguration(new ExampleEntityConfiguration());

  // lot more configurations here
}

Has anyone come across or knew a way to register all interfaces IEntityTypeConfiguration?

It just looks like a lot of repeating code that can be solved by getting a list of configurations, going through them and applying them in context. I just don’t know where to start by getting a list of classes IEntityTypeConfigurationthat exist in a particular namespace.

/ .

+11
5

:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);    
    // get ApplyConfiguration method with reflection
    var applyGenericMethod = typeof(ModelBuilder).GetMethod("ApplyConfiguration", BindingFlags.Instance | BindingFlags.Public);            
    // replace GetExecutingAssembly with assembly where your configurations are if necessary
    foreach (var type in Assembly.GetExecutingAssembly().GetTypes()
        .Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) 
    {
        // use type.Namespace to filter by namespace if necessary
        foreach (var iface in type.GetInterfaces()) {
            // if type implements interface IEntityTypeConfiguration<SomeEntity>
            if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)) {
                // make concrete ApplyConfiguration<SomeEntity> method
                var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                // and invoke that with fresh instance of your configuration type
                applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
                break;
            }
        }
    }
}
+12

@Evk kan :

 public static class ModelBuilderExtensions
{
    public static void ApplyAllConfigurationsFromCurrentAssembly(this ModelBuilder modelBuilder, Assembly assembly, string configNamespace = "")
    {
        var applyGenericMethods = typeof(ModelBuilder).GetMethods( BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy);
        var applyGenericApplyConfigurationMethods = applyGenericMethods.Where(m => m.IsGenericMethod && m.Name.Equals("ApplyConfiguration", StringComparison.OrdinalIgnoreCase));
        var applyGenericMethod = applyGenericApplyConfigurationMethods.Where(m=>m.GetParameters().FirstOrDefault().ParameterType.Name== "IEntityTypeConfiguration'1").FirstOrDefault();


        var applicableTypes = assembly
            .GetTypes()
            .Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters);

        if (!string.IsNullOrEmpty(configNamespace))
        {
            applicableTypes = applicableTypes.Where(c => c.Namespace == configNamespace);
        }

        foreach (var type in applicableTypes)
        {
            foreach (var iface in type.GetInterfaces())
            {
                // if type implements interface IEntityTypeConfiguration<SomeEntity>
                if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>))
                {
                    // make concrete ApplyConfiguration<SomeEntity> method
                    var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                    // and invoke that with fresh instance of your configuration type
                    applyConcreteMethod.Invoke(modelBuilder, new object[] { Activator.CreateInstance(type) });
                    Console.WriteLine("applied model " + type.Name);
                    break;
                }
            }
        }
    }
}

:

public class ApiDbContext : DbContext
{
    public DbSet<Customer> Customers { get; set; }
    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.ApplyAllConfigurationsFromCurrentAssembly("MyRoot.Api.Entities.Configuration");
    }
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
    }
}
+8

@Evk , @paul van bladel - , , . - , :

public static ModelBuilder ApplyAllConfigurationsFromAssembly(
    this ModelBuilder modelBuilder, Assembly assembly)
{   
    var applyGenericMethod = typeof(ModelBuilder)
        .GetMethods(BindingFlags.Instance | BindingFlags.Public)
        .Single(m => m.Name == nameof(ModelBuilder.ApplyConfiguration)
            && m.GetParameters().Count() == 1
            && m.GetParameters().Single().ParameterType.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>));        
    foreach (var type in assembly.GetTypes()
        .Where(c => c.IsClass && !c.IsAbstract && !c.ContainsGenericParameters)) 
    {
        foreach (var iface in type.GetInterfaces())
        {
            if (iface.IsConstructedGenericType && iface.GetGenericTypeDefinition() == typeof(IEntityTypeConfiguration<>)) 
            {
                var applyConcreteMethod = applyGenericMethod.MakeGenericMethod(iface.GenericTypeArguments[0]);
                applyConcreteMethod.Invoke(modelBuilder, new object[] {Activator.CreateInstance(type)});
                break;
            }
        }
    }
}

, , DbContext, :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.ApplyAllConfigurationsFromAssembly(GetType().Assembly);           
    base.OnModelCreating(modelBuilder);
}
+5

EF Core 2. 2+, :

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
   Assembly assemblyWithConfigurations = GetType().Assembly; //get whatever assembly you want
   modelBuilder.ApplyConfigurationsFromAssembly(assemblyWithConfigurations);
}
+1

I really like @paul van bladel's answer for moving code to an extension method. I also need to call this from other assemblies, so I created an enumeration and changed the applicable types, which will be set differently.

IEnumerable<Type> assemblyTypeList;

switch (pAssemblyMethodType)
{
    case AssemblyMethodType.CallingAssembly:
        assemblyTypeList = Assembly.GetCallingAssembly()
            .GetTypes()
            .Where(c => c.IsClass
                && !c.IsAbstract
                && !c.ContainsGenericParameters);
        break;
    case AssemblyMethodType.ExecutingAssembly:
        assemblyTypeList = Assembly.GetExecutingAssembly()
            .GetTypes()
            .Where(c => c.IsClass
                && !c.IsAbstract
                && !c.ContainsGenericParameters);
        break;
    default:
        throw new ArgumentOutOfRangeException(nameof(pAssemblyMethodType), pAssemblyMethodType, null);
}
0
source

Source: https://habr.com/ru/post/1688396/


All Articles