在 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/