EntityType' is a variable but is used like a type when use the Reflection

c# entity-framework-6 reflection

Question

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 ???

1
3
4/2/2019 10:18:19 AM

Accepted Answer

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.

2
4/2/2019 10:33:30 AM

Popular Answer

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



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow