代码之家  ›  专栏  ›  技术社区  ›  Krunal

从Linq DataContext中的表名获取表数据

  •  13
  • Krunal  · 技术社区  · 16 年前

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

    而不是这个

    var results = db.Authors;
    

    我需要这样做。

    string tableName = "Authors";
    
    var results = db[tableName];
    

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

    4 回复  |  直到 16 年前
        1
  •  15
  •   jason    13 年前

    鉴于 DataContext context 和 string tableName 你可以说:

    var table = (ITable)context.GetType()
                               .GetProperty(tableName)
                               .GetValue(context, null);
    
        2
  •  4
  •   Perpetualcoder    16 年前

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

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

    Here 是msdn文档。

        3
  •  3
  •   Terje    16 年前

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

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

    这将为您提供authors表,如pr.table。

        4
  •  0
  •   Ondrej Janacek    12 年前

    如果你知道类型,你可以把它铸造出来。从 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);
        }
    }