<分区>
我正在尝试执行一些 LINQ
使用动态表名的命令。例如,而不是:
var o = (from x in context.users select x);
我想使用类似的东西:
var o = (from x in getTableObjectByName("users", context) select x);
或多或少。这是我到目前为止的代码,可以编译和运行:
using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}
运行,但始终返回零记录。用户表肯定包含记录,并且在任何情况下,当我使用上面的第一种方法直接调用它时,我都会按预期获得所有记录。如何修改我的代码以实际拉取记录,而不仅仅是一个空集合?
编辑:我也试过这个:
using (MySiteEntities ipe = new MySiteEntities())
{
var prop = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
Type dbsetType = typeof(DbSet<>);
dbsetType = dbsetType.MakeGenericType(Type.GetType("MySiteNamespace.user"));
Type t = dbsetType.GetType();
var val = prop.GetValue(ipe, null);
}
在这种情况下,代码不仅会运行,而且会按预期返回结果。然而,val
是一个对象。我需要将其转换为 DbSet<user>
类型,这很容易,除了参数 user
仅在运行时已知....类型转换也需要是动态的。我试过使用 Convert.ChangeType(val, t);
, 但这会抛出一个
InvalidCastException (Object must implement IConvertible).
如何转换 val
实际可用对象的变量?
不知道这是否相关,但这是在 EntityFramework 4 上。