我有一个包含 100 多个表的 DataContext(Linq to Sql),是否可以获取所有这些表的列表,然后将它们打印到控制台?这可能是一个愚蠢的问题。
谢谢。
我有一个包含 100 多个表的 DataContext(Linq to Sql),是否可以获取所有这些表的列表,然后将它们打印到控制台?这可能是一个愚蠢的问题。
谢谢。
它比上面容易得多,不需要反射。Linq to SQL 有一个 Mapping 属性,您可以使用它来获取所有表的枚举。
context.Mapping.GetTables();
你可以通过反射来做到这一点。本质上,您遍历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);
}
}
}
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();
}