我正试图编写一个方法,将属性强制转换为DbSet,然后调用load方法。
我尝试过以下几种:
var value = propertyInfo.GetValue(em, null) as DbSet;
//Not working, because it always returns null
var value = propertyInfo.GetValue(em, null) as DbSet<T>;
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T')
var value = propertyInfo.GetValue(em, null) as DbSet<TEntity>;
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol TEntity')
但只有当我指定正确的类型时,它才能工作:
var value = propertyInfo.GetValue(em, null) as DbSet<TempTable>;
如何在不指定TempTable的情况下解决此问题?
var value = propertyInfo.GetValue(em, null) as DbSet;
//Not working, because it always returns null
的确;DbSet<TEntity>
不是从DbSet
继承的,所以是的,它将始终是null
。
//Not working, because its a syntax error and doesnt even compile (giving error 'Cannot resolve symbol T')
你需要知道与之交谈的东西的类型;您可以使用非通用的IEnumerable
/IQueryable
API,但我怀疑这里最合适的错误可能是dynamic
:
dynamic val = propertyInfo.GetValue(em, null);
EvilMethod(val);
//...
void EvilMethod<T>(DbSet<T> data)
{
// this will resolve, and you now know the `T` you are talking about as `T`
data.Load();
}
或者如果您只是想调用Load
:
dynamic val = propertyInfo.GetValue(em, null);
val.Load();
试试这个:
var value = propertyInfo.GetValue(em, null) as IQueryable;
value.Load();
可能是这样的:
var setMethod = typeof(MyDataContext)
.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance)
.Where(m => m.Name == "Set")
.Where(m => m.IsGenericMethod)
.Select(m => m.MakeGenericMethod(typeof(TEntity)))
.SingleOrDefault();
var value = setMethod.Invoke(myDataContextInstance, null);