如何在通用存储库中实现表达式删除?

问题描述 投票:0回答:1

一些细节。通用存储库包含方法 GetByCondition:

    public IQueryable<T> GetByCondition(Expression<Func<T, bool>> expression) => 
        DbContext.Set<T>().Where(expression).AsNoTracking();

如何实现按表达式删除?例如如下:

    public IQueryable<T> DeleteByCondition(Expression<Func<T, bool>> expression) =>
        DbContext.Set<T>().RemoveRange(expression);

现在它像这样实现:

public void Remove(T entity) => PintDbContext.Set<T>().RemoveRange(entity);

像下面这样调用:

var item = await repo.Test.GetByCondition(test => test.Id.Equals(testId))
myRepo.Test.Remove(item);

想像下面这样打电话:

DeleteByCondition(test => test.Id.Equals(testId))
c# entity-framework-core repository-pattern
1个回答
1
投票

您必须先检索实体,然后从

DbSet
中删除它们:

public void DeleteByCondition(Expression<Func<T, bool>> expression)
{
    var entitiesToDelete = DbContext.Set<T>().Where(expression).ToList();
    DbContext.Set<T>().RemoveRange(entitiesToDelete);
}
© www.soinside.com 2019 - 2024. All rights reserved.