启用 RemoveRange 以通过实体上的谓词删除

Jas*_*n W 0 c# linq entity-framework linq-expressions

在业务层中,删除与实体的关系时会出现大量重复代码,而实体本身正在被删除(没有对数据库进行级联删除的好处)。除了相关的实体删除用例之外,还可以使用一种好的方法来减少通过任何匹配谓词(例如通过 id 等)删除记录所需的代码。

// Simple example removing phone numbers from people entity
// The "personId" is an identifier passed into the method performing the deletion
var phones = _context.Phones
    .Where(m => m.PersonId == personId)
    .ToList();
if (phones.Count > 0)
    _context.Phones.RemoveRange(phones);
Run Code Online (Sandbox Code Playgroud)

我将此作为我想出的解决方案的问答发布,以便我以后可以查找。绝对希望看到其他方法。

Jas*_*n W 5

一种方法是使用表达式重载 DbSet 上的 RemoveRange 方法。为了尽可能方便,请将其作为 DbSet 实体本身的方法扩展来实现,以便使用实际的 RemoveRange 方法将该过程简单地重载到 DbSet 上。

public static class DataExtensions
{
    public static void RemoveRange<TEntity>(
        this System.Data.Entity.DbSet<TEntity> entities,
        System.Linq.Expressions.Expression<Func<TEntity, bool>> predicate)
        where TEntity : class
    {
        var records = entities
            .Where(predicate)
            .ToList();
        if (records.Count > 0)
            entities.RemoveRange(records);
    }
}
Run Code Online (Sandbox Code Playgroud)

有了这个扩展,现在可以类似于调用 RemoveRange Where

_context.Phones.RemoveRange(m => m.PersonId == personId);
Run Code Online (Sandbox Code Playgroud)