简体   繁体   English

对 EF Core 中的所有实体运行查询

[英]Running a query over all entities in EF Core

I have a base class for all entities:我对所有实体都有一个基础 class :

public abstract class Entity
{
    int Id { get; set; }

    bool Flagged { get; set; }
}

public class Foo : Entity
{
    string Name { get; set; }
}

public class Bar : Entity
{
    int Counter { get; set; }
}

I want to find all entities where Flagged is set to true, and then either modify them or remove them from the database.我想找到Flagged设置为 true 的所有实体,然后修改它们或从数据库中删除它们。 How do I do this without manually going over every DbSet for every derived type?如何在不手动检查每个派生类型的每个DbSet的情况下做到这一点?

The solution I came up with for updating the entities uses DbContext.Model.GetEntityTypes() to get all entity types, and MethodInfo.MakeGenericMethod to get the DbSet of each entity type.我想出的更新实体的解决方案使用DbContext.Model.GetEntityTypes()来获取所有实体类型,并使用MethodInfo.MakeGenericMethod来获取每个实体类型的DbSet Finally cast them to IQueryable<Entity> so I can access the entity without knowing the underlying type of the DbSet .最后将它们转换为IQueryable<Entity> ,这样我就可以在不知道DbSet的基础类型的情况下访问实体。

Using that I made the following extension methods:使用它我做了以下扩展方法:

public static IQueryable<Entity> GetEntityQuery(this DbContext context, Type entityType)
{
    MethodInfo method = typeof(DbContext).GetMethod(nameof(DbContext.Set));
    MethodInfo genericMethod = method.MakeGenericMethod(entityType);
    var dbSet = genericMethod.Invoke(context, null);
    return (IQueryable<Entity>)dbSet;
}

public static IEnumerable<IQueryable<Entity>> GetAllEntityQueries(this DbContext context)
{
    foreach (var entityType in context.Model.GetEntityTypes())
    {
        yield return context.GetEntityQuery(entityType.ClrType);
    }
}

For deleting I simply use the DbContext.Remove and DbContext.RemoveRange methods that take an object .对于删除,我只需使用采用objectDbContext.RemoveDbContext.RemoveRange方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM