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

问题描述 投票:7回答:5

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

谢谢。

.net linq asp.net-3.5 datacontext
5个回答
29
投票

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

context.Mapping.GetTables();

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);
        }
    }
}

4
投票
dc= new myDataContext();
var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList();

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);
        }
    }
}

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();
}
© www.soinside.com 2019 - 2024. All rights reserved.