Cast DbSet <t>并调用方法</t>

时间:2013-11-28 14:02:57

标签: c# .net entity-framework reflection

我正在尝试编写一个方法,将属性转换为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的情况下解决这个问题?

3 个答案:

答案 0 :(得分:3)

试试这个:

var value = propertyInfo.GetValue(em, null) as IQueryable;
value.Load();

答案 1 :(得分:3)

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();

答案 2 :(得分:1)

或许这样的事情:

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);