简体   繁体   中英

Running a query over all entities in EF Core

I have a base class for all entities:

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. How do I do this without manually going over every DbSet for every derived type?

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. Finally cast them to IQueryable<Entity> so I can access the entity without knowing the underlying type of the 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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