【发布时间】:2016-02-10 05:21:03
【问题描述】:
我需要从 mi DbContext 获取所有 TEntity 以从每个表中提取所有信息。我的桌子很少,信息很少。 我有这个代码,但不工作。
var dbSetPropertiesLocal = local.GetDbSetProperties();
foreach (var item in dbSetPropertiesLocal)
{
Type type = item.PropertyType; // This need get the type of the actual TEntity
var enumerable = GetLocal<type>(item.Name, local);
}
此方法按名称和指定的 DbContext 返回指定 DbSet 中的所有数据
public List<TEntity> GetLocal<TEntity>(string name, DbContext ctx)
{
var enumerable = (IEnumerable<TEntity>)(typeof([ClassNameOfMyContext]).GetProperty(name).GetValue(ctx, null));
return enumerable.ToList();
}
此方法从我的 DbContext 中获取属性。我用它来获取我的 DbContext 中的所有 DbSet
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;
var isDbSet = setType.IsGenericType && (typeof(IDbSet<>).IsAssignableFrom(setType.GetGenericTypeDefinition()) || setType.GetInterface(typeof(IDbSet<>).FullName) != null);
if (isDbSet)
dbSetProperties.Add(property);
}
return dbSetProperties;
}
【问题讨论】:
-
这段代码的目的是从你的 dbcontext 中的每个实体中获取所有数据?
-
是的,我正在做一个数据库同步器
-
像
context.Set<Users>().ToList()这样使用context.Set<T>().ToList();是不是容易多了 -
但是我不知道我的 DbContext 中有多少个 Entities,所以我需要做泛型。
-
可以使用第三方库还是受限?添加 TPC、TPH 和 TPT 继承时,查找所有表/属性可能会有点困难。
标签: c# entity-framework