目的:
我需要循环所有记录,例如:
var records = db.Set<UserAccount>().ToList();
然后循环
foreach (var record in records)
{
// do something with the record
}
但它必须在运行时不特定类型,因为我要循环类型,因此不知道示例“UserAccount”。
只有类型/TypeOf?
在这个描述的底部我有一个方法循环所有实体我找不到工作的方式
我创建了一个包含一些实体的 DbContext。
public class MyEntities : DbContext
{
public DbSet<UserAccount> UserAccounts { get; set;}
public DbSet<UserRole> UserRoles { get; set; }
public DbSet<UserAccountRole> UserAccountRoles { get; set; }
}
定义了一个Type列表来控制输出:
public static List<Type> ModelListSorted()
{
List<Type> modelListSorted = new List<Type>();
modelListSorted.Add(typeof(UserRole));
modelListSorted.Add(typeof(UserAccountRole));
modelListSorted.Add(typeof(UserAccount));
return modelListSorted;
}
问题出在下面,我找不到让它工作的方法:-(
public static loopAllEntities()
{
List<Type> modelListSorted = ModelHelper.ModelListSorted();
foreach (Type type in modelListSorted)
{
var records = ????? // get a list of records in the current table from type.
foreach (var record in records)
{
// do something with the record
}
}
}
我知道这是一个老问题,但问题没有指定 EF 版本,并且建议的答案对于 Entity Framework Core 不再有效(至少在本答案发布之日,DbContext 在 EF core 中没有非通用设置方法) 。
然而,您仍然可以使用 Jon Skeet 的答案来使用有效的扩展方法这个问题 https://stackoverflow.com/questions/4667981/c-sharp-use-system-type-as-generic-parameter。为了方便起见,我的代码添加在下面。
public static IQueryable Set(this DbContext context, Type T)
{
// Get the generic type definition
MethodInfo method = typeof(DbContext).GetMethod(nameof(DbContext.Set), BindingFlags.Public | BindingFlags.Instance);
// Build a method with the specific type argument you're interested in
method = method.MakeGenericMethod(T);
return method.Invoke(context, null) as IQueryable;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)