问题描述
我使用EF代码优先4.1。在我的申请现在我想通过使用泛型类型的WCF服务获取实体。我试图反映通用类型并调用 Tob DbSet 对象的方法。
这是我的代码:
public string GetAllEntries(string objectType)
{
try
{
var mdc =
Globals.DbConnection.Create(@some_db_connection,true);
//获取类型的汇编
var asob = Assembly.GetAssembly(typeof(CrmObject));
//从程序集获取请求的对象类型
var genericType = asob.GetType(objectType,true,true);
if(genericType.BaseType == typeof(CrmObject))
{
//获取集< T>方法
var method = mdc.GetType()。GetMember(Set)。Cast< MethodInfo>()。其中(x => x.IsGenericMethodDefinition).FirstOrDefault()
//使Set< SomeRealCrmObject>()方法
var genericMethod = method.MakeGenericMethod(genericType);
//将Setmethod调用到invokeSet
var invokeSet = genericMethod.Invoke(mdc,null);
//从Set<>调用ToList方法invokeSet
var invokeToList = invokeSet.GetType()。GetMember(ToList)。Cast< MethodInfo&()。FirstOrDefault();
//此返回未引用的对象作为结果
返回invokeToList.ToString();
}
返回null;
}
catch(Exception ex)
{
return ex.Message + Environment.NewLine + ex.StackTrace;
}
}
其实我写的代码就像 return mdc.Set< SomeRealCrmObject>()。ToList()
- 适用于我!但是,然后我使用通用类型,我找不到对象 DbSet< SomeRealCrmObject>()
中的ToList方法。
不是DbSet / ObjectSet的成员,但是是一种扩展方法。
您可以尝试这样做
var method = typeof(Enumerable).GetMethod(ToList);
var generic = method.MakeGenericMethod(genericType);
generic.Invoke(invokeSet,null);
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>()
.
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);
这篇关于反射+ Linq + DbSet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!