小编pla*_*ken的帖子

EF从Type获取运行时记录列表

目的:我需要循环所有记录,如:

var records = db.Set<UserAccount>().ToList();
Run Code Online (Sandbox Code Playgroud)

然后循环

foreach (var record in records)
{
    // do something with the record 
}
Run Code Online (Sandbox Code Playgroud)

但是它必须在运行时没有特定类型,因为我要遍历类型,因此不知道示例"UserAccount".只有Type/TypeOf?

在本说明书的底部,我有一个方法loopAllEntities,我找不到工作方式

我用一些实体创建了一个DbContext.

public class MyEntities : DbContext
{
    public DbSet<UserAccount> UserAccounts { get; set;}
    public DbSet<UserRole> UserRoles { get; set; }
    public DbSet<UserAccountRole> UserAccountRoles { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

定义了一个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;
}
Run Code Online (Sandbox Code Playgroud)

问题是在我无法找到方法使其工作:-(

public static loopAllEntities()
{
    List<Type> modelListSorted = ModelHelper.ModelListSorted();

    foreach (Type type …
Run Code Online (Sandbox Code Playgroud)

c# entity-framework typeof type-conversion dbcontext

5
推荐指数
1
解决办法
1350
查看次数