2016-02-04 66 views
2

我需要使用EF獲取數據庫中的所有表。我需要他們一個一個地一桌一桌地從每個桌子上提取一些信息。任何想法如何?如何從DbContext獲取所有DbSet

+0

您需要獲取所有DbSet或所有表嗎?你的問題與標題不清楚。 –

+0

DbSet與表格相同。 – Richard

+0

你爲什麼需要這樣做?如果使用EF,根據數據庫的大小,可能需要很長時間才能執行。 – mikeyq6

回答

6

這是我在EntityFramework Plus庫中使用的擴展方法。

using (var ctx = new TestContext()) 
{ 
    var dbSetProperties = ctx.GetDbSetProperties(); 
    List<object> dbSets = dbSetProperties.Select(x => x.GetValue(ctx, null)).ToList(); 
} 

public static class Extensions 
{ 
    public static List<PropertyInfo> GetDbSetProperties(this DbContext context) 
    { 
     var dbSetProperties = new List<PropertyInfo>(); 
     var properties = context.GetType().GetProperties(); 

     foreach (var property in properties) 
     { 
      var setType = property.PropertyType; 

#if EF5 || EF6 
      var isDbSet = setType.IsGenericType && (typeof (IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof (IDbSet<>).FullName) != null); 
#elif EF7 
      var isDbSet = setType.IsGenericType && (typeof (DbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition())); 
#endif 

      if (isDbSet) 
      { 
       dbSetProperties.Add(property); 
      } 
     } 

     return dbSetProperties; 

    } 
} 

編輯 您需要從DbSet元素類型使用反射和遍歷所有屬性。這不適用於TPC,TPT和TPH

要獲得更簡單的解決方案,請使用Entity Framework Extensions中的方法GetModel。這是這個庫的一個免費功能。

項目:Entity Framework Extensions

文檔:GetModel

免責聲明:我的項目實體框架擴展的所有者

+0

以及我如何遍歷每個表或DbSet的屬性? – Richard

0
EntityContainer container = ObjectContext.MetadataWorkspace.GetEntityContainer(ObjectContext.DefaultContainerName, DataSpace.CSpace); 
      List<string> result = (from meta in container.BaseEntitySets 
         where meta.BuiltInTypeKind == BuiltInTypeKind.EntitySet 
         select meta.ElementType.ToString()).ToList<string>(); 
-1

你可以使用這樣的事情得到一個列表的表格,然後循環瀏覽並獲取所需的信息:

var db = new myContext().GetAllTableProperties().ToList(); 
+1

GetAllTableProperties()。ToList();沒有出現 – Richard