3

i need to register all entity in DbContext .

i create a extention for register automatic all Entity with Reflection :

  public static void RegisterAllEntity<BaseType>(this DbModelBuilder builder, params Assembly[] assmblies)
    {
        IEnumerable<Type> types = assmblies.SelectMany(x => x.GetExportedTypes())
            .Where(x => x.IsClass && !x.IsAbstract && x.IsPublic && typeof(BaseType).IsAssignableFrom(x));

        foreach (Type EntityType in types)
            builder.Entity<EntityType>();
    }

but it show me this error :

EntityType' is a variable but is used like a type

in this line :

    foreach (Type EntityType in types)
            builder.Entity<EntityType>();

whats the problem ? how can i solve this problem ???

mr-dortaj
  • 782
  • 4
  • 11
  • 28

3 Answers3

2

Looking at the documentation I think you want to use DbModelBuilder.RegisterEntityType rather than DbModelBuilder.Entity. The documentation for the former says:

This method is provided as a convenience to allow entity types to be registered dynamically without the need to use MakeGenericMethod in order to call the normal generic Entity method.

So rather than builder.Entity<EntityType>(); you would instead use builder.RegisterEntityType(EntityType);

It is worth mentioning that often in situations like this there is a non-generic method that takes a Type object instead so if you find yourself in this situation with other software in the future check for that non-generic method with a Type parameter.

Chris
  • 27,210
  • 6
  • 71
  • 92
1

Generic Arguments need to be resolvable during compilation. You need to use reflection to call Entity method in such loop. Please check this anwser.

Example of usage

...
MethodInfo method = typeof(DbModelBuilder).GetMethod("Entity");
MethodInfo generic = method.MakeGenericMethod(EntityType);
generic.Invoke(builder, null);

EDIT:

Also as Chris mentioned, there is no need to use reflection because DbModelBuilder provide RegisterEntityType method, which accept Type as argument, eg:

builder.RegisterEntityType(EntityType);

EDIT2: there's Chris' answer

M. Galczynski
  • 634
  • 1
  • 5
  • 12
  • 1
    No need to use reflection - DBModelBuilder provides a method (RegisterEntityType) that takes a `Type` as a parameter and explicitly says it exists to allow you to register things without he need to use `MakeGenericMethod`. – Chris Apr 02 '19 at 10:34
1

You use EntityType as a variable in foreach cycle, and EntityType like type in builder.Entity<EntityType>(). Change variable name from EntityType to entityType for example so C# compiler could understand your code

NoImagination
  • 178
  • 1
  • 8