【发布时间】:2010-10-18 16:21:35
【问题描述】:
我有一个包含 100 多个表的 DataContext(Linq to Sql),是否可以获取所有这些表的列表,然后将它们打印到控制台?这可能是一个愚蠢的问题。
谢谢。
【问题讨论】:
标签: .net linq asp.net-3.5 datacontext
我有一个包含 100 多个表的 DataContext(Linq to Sql),是否可以获取所有这些表的列表,然后将它们打印到控制台?这可能是一个愚蠢的问题。
谢谢。
【问题讨论】:
标签: .net linq asp.net-3.5 datacontext
您可以通过反射来做到这一点。本质上,您遍历 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 有一个 Mapping 属性,您可以使用它来获取所有表的枚举。
context.Mapping.GetTables();
【讨论】:
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);
}
}
}
【讨论】:
对于 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();
}
【讨论】: