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

pla*_*ken 5 c# entity-framework typeof type-conversion dbcontext

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

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 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
        } 
    }
}
Run Code Online (Sandbox Code Playgroud)

Mat*_*ers 1

看起来您已经快完成了,您应该能够执行以下操作:

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

        foreach (Type type in modelListSorted) 
        {
            var records = dbContext.Set(type);
            // do something with the set here
        }
    }
Run Code Online (Sandbox Code Playgroud)

这将为您提供一个非通用的集合来使用。这取决于您想要做什么,因为该集合没有类型,它可能会有点棘手,可能会转换为基本类型或接口来使用?

编辑:我没有足够的声誉来发表评论,但 Mayoors 解决方案将让您得到您想要的东西,而无需使用非通用类型并预先获得整个集合。