我需要从Linq DataContext中获取表名对应的表格数据。
不使用下面的方法:
var results = db.Authors;
我需要做类似这样的事情。
string tableName = "Authors";
var results = db[tableName];
它可以是DataContext中可用的任何表名。
我需要从Linq DataContext中获取表名对应的表格数据。
不使用下面的方法:
var results = db.Authors;
我需要做类似这样的事情。
string tableName = "Authors";
var results = db[tableName];
它可以是DataContext中可用的任何表名。
如果给定了DataContext context
和string tableName
,你可以只需说:
var table = (ITable)context.GetType()
.GetProperty(tableName)
.GetValue(context, null);
我不确定传递字符串是否是一个优雅的解决方案。我更愿意将实体类型作为参数发送到方法中。大致如下:
var table = _dataCont.GetTable(typeof(Customer));
MyDBContext db = new MyDBContext();
Type t = db.GetType();
PropertyInfo p = t.GetProperty("Authors");
var table = p.GetValue(db, null);
table
类型为一个 object
对象;在使用前需要将其强制转换成一个 ITable
。 - jason如果您知道类型,可以将其转换。来自http://social.msdn.microsoft.com/Forums/en-US/f5e5f3c8-ac3a-49c7-8dd2-e248c8736ffd/using-variable-table-name-in-linq-syntax?forum=linqprojectgeneral
MyDataContext db = new MyDataContext();
Assembly assembly = Assembly.GetExecutingAssembly();
Type t = assembly.GetType("Namespace." + strTableName);
if (t != null)
{
var foos = db.GetTable(t);
foreach (var f in foos)
{
PropertyInfo pi = f.GetType().GetProperty("Foo");
int value = (int)pi.GetValue(f, null);
Console.WriteLine(value);
}
}
ITable
也是一个IEnumerable
,因此可以使用你喜欢的方法枚举记录(例如,foreach(object r in tbl) { }
)。 - jason