DbContext.Set 和 DbContext.Set(string name) 是 EF Core 中唯一可用的函数。根据我所了解的,DbContext.Set(Type) 适用于 Framework。了解这一限制,我们将能够触发它。
public List<Type> FetchDbSetTypes()
{
var properties = dbContext.GetType().GetProperties();
var dbSets = new List<Type>();
foreach (var property in properties)
{
var propertyType = property.PropertyType;
if(propertyType.IsGenericType && propertyType.Name.ToLower().Contains("dbset"))
{
Type dbSetType = propertyType.GenericTypeArguments[0];
dbSets.Add(dbSetType);
}
}
return dbSets;
}
现在我们拥有了DBSets定义的强类型列表。接下来,我们需要根据添加的类型欺骗集合。唯一的方法是将该类型的对象作为参数传递。
这需要使用
反射,InternalDbSet<>,DBContext和动态。
List<Type> dbsetTypes = FetchDbSetTypes();
dbsetTypes.ForEach(async dbsetType =>
{
try
{
Type myType = typeof(InternalDbSet<>).MakeGenericType(dbsetType);
dynamic instance = Activator.CreateInstance(myType, context, dbsetType.Name);
var test = await FetchFromTable(instance, 0, 10);
}
catch(Exception)
{
}
});
然后我们调用涉及DbSet的通用方法
public async Task<List<T>> FetchFromTable<T>(DbSet<T> _, int skip = 0, int fetchSize = 10000) where T : class
{
//DbSet<T> parameter is not needed - it will throw an Exception
return await dbContext.Set<T>().Skip(skip).Take(fetchSize).ToListAsync();
}
注意:确保您的 DbContext 属性具有 getters
dbSet
进行for循环,由于它是IQueryable
类型,我无法获取dbSet
内部的属性。 我该如何解决这个问题? - bbusdriverIQueryable
不能提供您所需的内容,请使用提供该内容的接口。我不确定您想要实现什么。 - Moho.Add
或.Remove
,看起来这两个方法都不属于任何接口...希望我是错的! - bunjeeb