linq中的动态表名
我正在尝试使用动态表名执行一些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); }
运行,但始终返回零记录。 users表最肯定包含记录,在任何情况下,当我使用上面的第一种方法直接调用它时,我会按预期获得所有记录。 如何修改我的代码以实际记下记录,而不仅仅是空集合?
编辑:我也试过这个:
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
是一个Object。 我需要将它转换为类型DbSet
,这很容易,除了参数user
只在运行时已知….演员也需要是动态的。 我尝试过使用Convert.ChangeType(val, t);
但是那会抛出一个
InvalidCastException(Object必须实现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)); }
你可以这样查询:
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 }
有关System.Linq.Dynamic的更多信息,请访问此处
上述就是C#学习教程:linq中的动态表名分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注---计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1026989.html