EF 核心。如何从深度嵌套实体中仅加载必要的属性

Use*_*ser 5 c# entity-framework-core

我开发了一个简单的应用程序,类似于聊天,其中每条消息都可能包含文本和文件。实体之间的关系如下:

消息组 -> 每个消息组都有一个消息集合 -> 每条消息都有一个属性“FileCollection” -> “文件集合”有 4 个集合:图像、视频、音频、文件。它们在数据库中都有相同的关系。为了在此处显示此逻辑,我的查询是获取所有消息组及其实体:

var messageGroups = await _db.MessageGroups
    .Where(mg => mg.UserId == id)
    .Include(m => m.Messages).ThenInclude(mes => mes.FileCollection.Images)
    .Include(m => m.Messages).ThenInclude(mes => mes.FileCollection.Video)
    .Include(m => m.Messages).ThenInclude(mes => mes.FileCollection.Audio)
    .Include(m => m.Messages).ThenInclude(mes => mes.FileCollection.Files)
    .ToListAsync();
Run Code Online (Sandbox Code Playgroud)

问题是每种类型的文件(图像、音频等)在 Db(EF Core 中的属性)中都有一个“数据”列,其中包含其 blob 数据。我想从查询中排除所有 blob,因为从数据库加载所有用户文件的查询变得非常繁重。像这样的东西(但排除方法不存在):

.Include(m => m.Messages).ThenInclude(mes => mes.FileCollection.Video).exclude(video => video.Data);
Run Code Online (Sandbox Code Playgroud)

有没有办法在查询结束时使用显式加载?或者也许有像 [JsonIgnore] 这样的属性,它从 Json 序列化中排除类属性?或者有其他方法吗?

如果有帮助:ImageFile、AudioFile 等继承自 File 超类:

public class File
{
    [Column("id")]
    public int Id { get; set; }

    [Column("content_type")]
    public string ContentType { get; set; }

    [Column("file_name")]
    public string FileName { get; set; }

    [Column("length")]
    public long Length { get; set; }

    [Column("related_file_collection_id")]
    public int FileCollectionId { get; set; }

    public FileCollection FileCollection { get; set; }
}


public class ImageFile : File
{
    [Column("data")]
    public byte[] Data { get; set; }

}
Run Code Online (Sandbox Code Playgroud)

我需要“文件”类中的所有属性,而不需要其子类中的“数据”属性。

Kri*_*ica 0

您可以使用该[NotMapped]属性,但随后您将无法从其他查询的数据库中检索该列。

您还可以创建 DTO 并仅选择所需的属性,但考虑到您的所有包含内容,这并不优雅。