jeudi 17 novembre 2016

relection entity framework mapping

Hi my question is it possible? and if so how? to have results from a query using entityframework populated with fully typed objects when initialized using reflection?

The conditions are the context and entities must be able to be in an external dll not referenced directly in the project.

I do not want to have to manually loop through the object graph and reflect all types.

This is the code I have currently.

 Assembly metaAssembly = AppDomain.CurrentDomain.GetAssemblies().
       SingleOrDefault(assembly => assembly.GetName().Name == "Data_Meta");
        TypeHelper myTypeHelper = new TypeHelper();
        Type dbContextType = myTypeHelper.FindDerivedTypes(metaAssembly, typeof(System.Data.Entity.DbContext)).ToList().FirstOrDefault();
        using (var ctx = (DbContext)Activator.CreateInstance(dbContextType))
        {
            ctx.Configuration.LazyLoadingEnabled = false;

            var curEntityPI = ctx.GetType().GetProperties().Where(pr => pr.Name == "Worker").First();
            var curEntityType = curEntityPI.PropertyType.GetGenericArguments().First();
            var set = ctx.Set(curEntityType);
            var t = set.ToString();
            Type generic = typeof(DataAccess.Models.Repository.EF.GenericEfDataRepository<,>);
            Type[] typeArgs = { curEntityType, dbContextType };
            Type constructed = generic.MakeGenericType(typeArgs);
            MethodInfo methodInfo = constructed.GetMethod("GetAll");
            object repositoryInstance = Activator.CreateInstance(constructed, new object[] { ctx });
            var navigationPropertyType = typeof(Expression<>).MakeGenericType(
typeof(Func<,>).MakeGenericType(curEntityType, typeof(object)));

            var navigationProperties = Array.CreateInstance(navigationPropertyType, 0);
            var result = methodInfo.Invoke(repositoryInstance, new object[] { navigationProperties });


        }

I can generate a database query and get the correct number of results, however items in the list returned to do not evaluate to a type unles I put a reference in the project to the dll which defeats my purpose. I should say I am resolving the location of the dll and loading it via the AppDomain.CurrentDomain.AssemblyResolve event.

Many thanks





Aucun commentaire:

Enregistrer un commentaire