Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reflection + Linq + DbSet

I use EF code-first 4.1. in my application. Now I want to get entities through WCF services using generic types. I'm trying to reflect generic type and invoke the method ToList of DbSet Object. Here is my code:

 public string GetAllEntries(string objectType)
        {
            try
            {
             var   mdc =
                   Globals.DbConnection.Create(@"some_db_connection", true);

               // Getting assembly for types
                var asob = Assembly.GetAssembly(typeof(CrmObject));
               // getting requested object type from assembly
                var genericType = asob.GetType(objectType, true, true);

                if (genericType.BaseType == typeof(CrmObject))
                {
                    // Getting Set<T> method
                    var method = mdc.GetType().GetMember("Set").Cast<MethodInfo>().Where(x => x.IsGenericMethodDefinition).FirstOrDefault();

                   // Making Set<SomeRealCrmObject>() method
                    var genericMethod = method.MakeGenericMethod(genericType);
                   // invoking Setmethod into invokeSet 
                    var invokeSet = genericMethod.Invoke(mdc, null);
                   // invoking ToList method from Set<> invokeSet 
                    var invokeToList = invokeSet.GetType().GetMember("ToList").Cast<MethodInfo>().FirstOrDefault();

                    //this return not referenced object as result
                    return invokeToList.ToString();
                }

                return null;
            }
            catch (Exception ex)
            {
                return ex.Message + Environment.NewLine + ex.StackTrace;
            }
        }

In fact then I write the code like return mdc.Set<SomeRealCrmObject>().ToList() - works fine for me! But then I use the generic types I cannot find the method ToList in object DbSet<SomeRealCrmObject>().

like image 678
DolceVita Avatar asked Dec 17 '22 13:12

DolceVita


2 Answers

Eranga is correct, but this is an easier usage:

dynamic invokeSet = genericMethod.Invoke(mdc, null);
var list = Enumerable.ToList(invokeSet);

C# 4's dynamic takes care of the cumbersome generic reflection for you.

like image 152
Diego Mijelshon Avatar answered Jan 04 '23 20:01

Diego Mijelshon


ToLIst() is not a member of DbSet/ObjectSet but is an extension method.

You can try this instead

var method = typeof(Enumerable).GetMethod("ToList");
var generic = method.MakeGenericMethod(genericType);
generic.Invoke(invokeSet, null);
like image 44
Eranga Avatar answered Jan 04 '23 19:01

Eranga