8

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

谢谢。

4

5 回答 5

30

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

context.Mapping.GetTables();
于 2009-04-10T00:22:19.640 回答
4

你可以通过反射来做到这一点。本质上,您遍历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);
        }
    }
}
于 2009-04-09T23:04:42.823 回答
4
dc= new myDataContext();
var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList();
于 2011-12-19T04:31:57.023 回答
1
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);
        }
    }
}
于 2012-07-09T09:18:30.123 回答
0

为 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();
}
于 2019-04-25T19:26:35.160 回答