Linq: Get a list of all tables within DataContext

六月ゝ 毕业季﹏ 提交于 2019-11-30 07:26:30

It's much easier than above and no reflection required. Linq to SQL has a Mapping property that you can use to get an enumeration of all the tables.

context.Mapping.GetTables();

You can do this via reflection. Essentially, you iterate over the properties in your DataContext class. For each property, check to see if that property's generic parameter type has the TableAttribute attribute. If so, that property represents a table:

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);
        }
    }
}
Just a Friend
dc= new myDataContext();
var listaTablas = (from tables in dc.Mapping.GetTables() select tables.TableName).ToList();
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);
        }
    }
}

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

for Tables

foreach (var table in Mapping.GetTables().Where(t => t.TableName.ToLower().Contains("push")))
{
    table.TableName.Dump();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!