Dot-Net

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

  • April 25, 2019

我有一個包含 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);
       }
   }
}

引用自:https://stackoverflow.com/questions/736174