【问题标题】:Linq: Get a list of all tables within DataContextLinq:获取 DataContext 中所有表的列表
【发布时间】:2010-10-18 16:21:35
【问题描述】:

我有一个包含 100 多个表的 DataContext(Linq to Sql),是否可以获取所有这些表的列表,然后将它们打印到控制台?这可能是一个愚蠢的问题。

谢谢。

【问题讨论】:

    标签: .net linq asp.net-3.5 datacontext


    【解决方案1】:

    您可以通过反射来做到这一点。本质上,您遍历 DataContext 类中的属性。对于每个属性,检查该属性的通用参数类型是否具有TableAttribute 属性。如果是这样,则该属性表示一个表:

    using System.Reflection;
    using System.Data.Linq.Mappings;
    
    PropertyInfo[] properties = typeof(MyDataContext).GetProperties();
    foreach (PropertyInfo property in properties)
    {
        if(property.PropertyType.IsGenericType)
        {
            object[] attribs = property.PropertyType.GetGenericArguments()[0].GetCustomAttributes(typeof(TableAttribute), false);
            if(attribs.Length > 0)
            {
                Console.WriteLine(property.Name);
            }
        }
    }
    

    【讨论】:

    • 快,但是当映射属性在 Linq to SQL 中时有点过于复杂。
    【解决方案2】:

    它比上面的要容易得多,并且不需要反射。 Linq to SQL 有一个 Mapping 属性,您可以使用它来获取所有表的枚举。

    context.Mapping.GetTables();
    

    【讨论】:

    • 其实这也给你看
    • 这似乎不是给你“System.Data.Linq.Table”而是“System.Data.Linq.Mapping.MetaTable”s
    【解决方案3】:
    dc= new myDataContext();
    var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList();
    

    【讨论】:

      【解决方案4】:
      using System.Reflection;
      using System.Data.Linq.Mappings;
      
      PropertyInfo[] properties = typeof(MyDataContext).GetProperties();
      foreach (PropertyInfo property in properties)
      {
          if(property.PropertyType.IsGenericType)
          {
              object[] attribs = property.PropertyType.GetGenericArguments()[0].GetCustomAttributes(typeof(TableAttribute), false);
              if(attribs.Length > 0)
              {
                  Console.WriteLine(property.Name);
              }
          }
      }
      

      【讨论】:

        【解决方案5】:

        对于 SP

        foreach (var sp in Mapping.ContextType.GetMembers().Where(w=> w.Name.ToLower().Contains("push")).GroupBy(g=>g.Name).Select(s=>s.First()))
        {
            sp.Name.Dump();
            sp.ToString().Replace("LINQPad.Return", "").Replace("System.Data.Linq.", "").Dump();
        }
        

        用于表格

        foreach (var table in Mapping.GetTables().Where(t => t.TableName.ToLower().Contains("push")))
        {
            table.TableName.Dump();
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2011-03-17
          • 1970-01-01
          • 2011-11-06
          • 2016-07-10
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多