从LINQ DataContext中的table-name获取表数据

时间:2009-12-17 05:21:07

标签: c# linq linq-to-sql

我需要从Linq DataContext的表名中获取表数据。

而不是这个

var results = db.Authors;

我需要做这样的事情。

string tableName = "Authors";

var results = db[tableName];

它可以是DataContext中可用的任何表名。

4 个答案:

答案 0 :(得分:15)

鉴于DataContext contextstring tableName,您只需说:

var table = (ITable)context.GetType()
                           .GetProperty(tableName)
                           .GetValue(context, null);

答案 1 :(得分:4)

我不确定传递字符串是否是一个优雅的解决方案。我宁愿将实体类型作为参数发送给方法。这些方面的东西:

var table = _dataCont.GetTable(typeof(Customer));

Here是MSDN文档。

答案 2 :(得分:3)

我不确定我是否认为它是一个好的解决方案,但如果你真的需要它,你可以这样做:

MyDBContext db = new MyDBContext();
Type t = db.GetType();
PropertyInfo p = t.GetProperty("Authors");
var table = p.GetValue(db, null);

这会给你作者表,作为pr。表

答案 3 :(得分:0)

如果您知道类型,可以投射它。来自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);
    }
}