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
免责声明:我是项目实体框架扩展的所有者
| 归档时间: |
|
| 查看次数: |
11899 次 |
| 最近记录: |