linq-to-entities - 删除实体而不将它们加载到内存中

标签 linq-to-entities entity-framework-core

在 Entity Framework Core 中,我有以下实体:

public class File {
  public Int32 Id { get; set; }
  public Byte[] Content { get; set; }
  public String Name { get; set; }
}

我有一个需要删除的文件 ID 列表:
List<Int32> ids = new List<Int32> { 4, 6, 8 }; // Ids example

如何在不加载每个文件内容属性的情况下删除 3 个文件?
_context.Files.Remove(??);

我不想加载每个文件内容属性,因为它的大小很大。

最佳答案

如果您确定数据库中存在所有 Id 并且上下文不包含(不跟踪)具有相同键的其他实体,则可以使用简单的假( stub )实体:

_context.RemoveRange(ids.Select(id => new File { Id = id }));

为避免不存在的 id 出现问题,您可以从数据库中获取现有的 id:
var existingIds = _context.Files.Where(f => ids.Contains(f.Id)).Select(f => f.Id).ToList();

_context.RemoveRange(existingIds.Select(id => new File { Id = id }));

为了避免跟踪实体问题,您可以使用 FindTracked自定义扩展方法来自我对 Delete loaded and unloaded objects by ID in EntityFrameworkCore 的回答并将其与上述任何一项结合起来。
var existingIds = _context.Files.Where(f => ids.Contains(f.Id)).Select(f => f.Id).ToList();

_context.RemoveRange(
    existingIds.Select(id => _context.FindTracked(id) ?? new File { Id = id }));

关于linq-to-entities - 删除实体而不将它们加载到内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48443370/

相关文章:

c# - 如何仅比较 EF 中 DateTime 的日期组件?

mysql - Entity Framework 添加方法不可用

c# - 使用 Entity Framework 选择一个范围

c# - 如何解决 DbContext 中的循环依赖

c# - EF Core “Invalid column name ' 鉴别器“继承错误”

c# - EF Code First DbContext 仅为集合的第一个元素返回封装的实体

c# - 选择对象的子子项

c# - Entity Framework 7 与 .Net 中的现有数据库 MVC 6

c# - EFCore 中的 Npgsql 无法翻译 DateTimeOffset.Date

c# - EF Core 3.0 SumAsync 触发聚合函数异常