【问题标题】:Dynamic table names动态表名
【发布时间】:2011-05-11 18:27:09
【问题描述】:

我有一个我的程序将查询的数据库。

它有 3 个表都具有相同的结构: 表1、表2、表3

如何编写一个 linq 查询来查询这些表中的每一个,并动态指定表名?

除此之外。如果将其他表添加到数据库中,此解决方案必须有效。因此,即使我在编写代码时 table4 不存在,它也可能会被添加。

【问题讨论】:

  • 是否可以创建一个表名数组,然后从中提取(即在表名数组上使用 foreach,然后将该数组元素作为名字)?
  • Some hacks are talked about here。 YMMV。祝你好运。
  • 如果表都具有相同的结构,为什么不只有一个表,额外的列指示记录的“类型”(之前由记录所属的表指示)?然后您就可以在 LINQ 查询的 where 子句中指定记录“类型”。
  • 我怕添加的行会拖慢查询不?

标签: c# .net linq linq-to-entities


【解决方案1】:

试试这个:

      DataSet s = new DataSet ();
      DataTable t1 = new DataTable ();
      t1.Columns.Add ("A", typeof (int));
      t1.Columns.Add ("B", typeof (string));
      s.Tables.Add (t1);
      t1.Rows.Add (1, "T1");
      t1.Rows.Add (2, "T1");

      DataTable t2 = new DataTable ();
      t2.Columns.Add ("A", typeof (int));
      t2.Columns.Add ("B", typeof (string));
      s.Tables.Add (t2);
      t2.Rows.Add (1, "T2");
      t2.Rows.Add (2, "T2");
      t2.Rows.Add (3, "T2");

      var result = from t in s.Tables.OfType<DataTable> ()
                   from r in t.Rows.OfType<DataRow> ()
                   select r;

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2012-12-05
    • 2011-04-10
    • 2018-02-01
    • 2017-11-08
    • 2013-08-13
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多