Rus*_*Uhl 1 c# linq reflection entity-framework
我正在尝试LINQ使用动态表名执行一些命令。例如,代替:
var o = (from x in context.users select x);
Run Code Online (Sandbox Code Playgroud)
我想使用类似:
var o = (from x in getTableObjectByName("users", context) select x);
Run Code Online (Sandbox Code Playgroud)
或多或少。到目前为止,这是我编译和运行的代码:
using (MySiteEntities ipe2 = new MySiteEntities()) {
var propinfo1 = Type.GetType("MySiteNamespace.MySiteEntities").GetProperty("users");
var propval1 = propinfo1.GetValue(ipe2, null);
}
Run Code Online (Sandbox Code Playgroud)
运行,但始终返回零记录。用户表最明确地包含记录,无论如何,当我直接使用上述第一种方法直接调用它时,都会得到所有记录。如何修改代码以实际提取记录,而不仅仅是空集合?
编辑:我也尝试过:
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);
}
Run Code Online (Sandbox Code Playgroud)
在这种情况下,代码不仅会运行,而且实际上会按预期返回结果。但是,val是一个对象。我需要将其强制转换为type DbSet<user>,这很容易,除了该参数user仅在运行时才知道....强制转换也必须是动态的。我尝试使用Convert.ChangeType(val, t);,但是会抛出一个
InvalidCastException(对象必须实现IConvertible)。
如何将val变量转换为实际可用的对象?
不知道这是否相关,但这在EntityFramework 4上。
在您的DbContext类中,添加一个称为Set的方法,该方法返回:
public DbSet Set(string name)
{
// you may need to fill in the namespace of your context
return base.Set(Type.GetType(name));
}
Run Code Online (Sandbox Code Playgroud)
您可以像这样查询:
using (var db = new YourDataContext())
{
// Since your DbSet isn't generic, you can can't use this:
// db.Set("Namespace.EntityName").AsQueryable().Where(a=> a.HasSomeValue...
// Your queries should also be string based.
// Use the System.Linq.Dynamic nuget package/namespace
var results = db.Set("Namespace.EntityName")
.AsQueryable()
.Where("SomeProperty > @1 and SomeThing < @2", aValue, anotherValue);
// you can now iterate over the results collection of objects
}
Run Code Online (Sandbox Code Playgroud)
有关System.Linq.Dynamic的更多信息,请参见此处。
| 归档时间: |
|
| 查看次数: |
12275 次 |
| 最近记录: |