删除实体而不将其加载到内存中 [英] Delete entities without loading them into memory
问题描述
在Entity Framework Core中,我具有以下实体:
In Entity Framework Core I have the following Entity:
public class File {
public Int32 Id { get; set; }
public Byte[] Content { get; set; }
public String Name { get; set; }
}
我有一个需要删除的文件ID列表:
And I have a list of files ids which I need to delete:
List<Int32> ids = new List<Int32> { 4, 6, 8 }; // Ids example
如何在不加载每个文件的Content属性的情况下删除这3个文件?
How can I delete the 3 files without loading each file Content property?
_context.Files.Remove(??);
我不想加载每个文件的Content属性,因为它的大小很大.
I do not want to load each file Content property as it is big in size.
推荐答案
如果您确定数据库中存在所有ID,并且上下文不包含(不跟踪)具有相同键的其他实体,则可以使用简单的伪造( stub )实体:
If you are sure the all Ids exist in the database and context does not contain (is not tracking) other entities with the same keys, you can use simple fake (stub) entities:
_context.RemoveRange(ids.Select(id => new File { Id = id }));
为避免不存在的ID出现问题,您可以从数据库中获取现有的ID:
To avoid problem with non existing ids, you can get the existing ids from the database:
var existingIds = _context.Files.Where(f => ids.Contains(f.Id)).Select(f => f.Id).ToList();
_context.RemoveRange(existingIds.Select(id => new File { Id = id }));
To avoid tracking entity problem, you can use the FindTracked
custom extension method from my answer to Delete loaded and unloaded objects by ID in EntityFrameworkCore and combine it with any of the above.
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 }));
这篇关于删除实体而不将其加载到内存中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!