如何从DbContext获取所有DbSet

Ric*_*ard 5 c# entity-framework

我需要使用EF获取数据库中的所有表.我需要他们逐桌走,并从每个提取某些信息.知道怎么样?

Jon*_*nan 12

这是我在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;

    }
}
Run Code Online (Sandbox Code Playgroud)

编辑 您需要使用DbSet元素类型的反射并迭代所有属性.这不适用于TPC,TPT和TPH

有关更简单的解决方案,请使用Entity Framework Extensions中的GetModel方法.这是该库的免费功能.

项目:实体框架扩展

文档:GetModel

免责声明:我是项目实体框架扩展的所有者

  • 以及如何遍历每个表或 DbSet 的属性? (2认同)