C# 从 LINQ DataContext 中的表名获取表数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1919632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 21:50:21  来源:igfitidea点击:

Get table-data from table-name in LINQ DataContext

c#linqlinq-to-sql

提问by Krunal

I need to get table data from table name from Linq DataContext.

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

Instead of this

而不是这个

var results = db.Authors;

I need to do something like this.

我需要做这样的事情。

string tableName = "Authors";

var results = db[tableName];

It could be any table name that is available in DataContext.

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

采纳答案by jason

Given DataContext contextand string tableName, you can just say:

鉴于DataContext contextand string tableName,你可以说:

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

回答by Perpetualcoder

I am not sure if passing strings is an elegant solution. I would rather send the Type of entity as an argument to a method. Something on these lines :

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

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

Hereis the MSDN documentation.

是 MSDN 文档。

回答by Terje

I am not sure I'd suggest it as a GOOD solution, but if you really need it, you could do something like this:

我不确定我会推荐它作为一个好的解决方案,但如果你真的需要它,你可以做这样的事情:

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

That will give you the Authors table, as pr. Table.

这将为您提供 Authors 表,作为 pr。桌子。

回答by DharmaTurtle

If you know the type, you can cast it. From http://social.msdn.microsoft.com/Forums/en-US/f5e5f3c8-ac3a-49c7-8dd2-e248c8736ffd/using-variable-table-name-in-linq-syntax?forum=linqprojectgeneral

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