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

linq:获取DataContext中所有表的列表

  •  7
  • Sergey  · 技术社区  · 17 年前

    我有一个数据上下文(linq-to-sql),有超过100个表,有没有可能得到所有这些表的列表,比如说打印到控制台?这可能是个愚蠢的问题。

    谢谢。

    4 回复  |  直到 13 年前
        1
  •  28
  •   Jacob Proffitt    17 年前

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

    context.Mapping.GetTables();
    
        2
  •  4
  •   Rex M    17 年前

    你可以通过反射来做到这一点。本质上,您迭代 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);
            }
        }
    }
    
        3
  •  3
  •   Mark Hall    14 年前
    dc= new myDataContext();
    var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList();
    
        4
  •  1
  •   dragon123    13 年前
    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);
            }
        }
    }
    
    推荐文章