繁体   English   中英

从包含中排除属性

[英]Exclude Property From Include

我的模型如下所示:

public class Note
{
    public long? ID { get; set; }
    public long AuthorID { get; set; }
    public virtual ICollection<Image> Images { get; set; }
    ...
}

public class Image
{
    public long? ID { get; set; }
    public byte[] Thumbnail { get; set; }
    public byte[] FullRes { get; set; }
}

我可以加载以下内容:

List<Note> a = dBContext.Notes.Where(x => x.AuthorID == myId)
        .Include(x => x.Images).ToList();

但是,我想避免加载 Image 的 FullRes 成员,因为它很大。 类似于以下内容(引发 ArgumentException - 包含路径表达式必须引用在类型上定义的导航属性。使用虚线路径作为参考导航属性,使用 Select 运算符作为集合导航属性。):

List<Note> a = dBContext.Notes.Where(x => x.AuthorID == myId)
        .Include(x => x.Images.Select(i => new Image
        {
            ID = i.ID,
            Thumbnail = i.Thumbnail
        })).ToList();

有谁知道实现这个目标的正确语法?

我没有测试它。 你可以试试这样的。

var notes = dBContext.Notes.Where(x => x.AuthorID == myId)
.Select(x=> new {
    x.ID,
    x.AuthorID,
    Images = x.Images.Select(i=> new {
        i.ID,
        i.Thumbnail
    }).ToList()
}).ToList();

// Rewrite
List<Note> a = notes.Select(x=> new Note{
    x.ID,
    x.AuthorID,
    Images = x.Images.Select(i=> new Image{
        i.ID,
        i.Thumbnail
    }).ToList()
}).ToList();

AFAIK ATM 的唯一方法是在查询中使用Select

List<Note> a = dBContext.Notes
    .Where(x => x.AuthorID == myId)
    .Select(x => new Note
    {
        ... select all note props,
        Images = x.Images.Select(i => new Image
        {
            ID = i.ID,
            Thumbnail = i.Thumbnail
        }
        .ToList()
    })
    .ToList();

UPD

错过了您使用的是 EF6。 然后,恐怕您不仅需要使用Select ,还需要自定义 DTO/匿名类,例如:

var a = dBContext.Notes
    .Where(x => x.AuthorID == myId)
    .Select(x => new 
    {
        ... select all note props,
        Images = x.Images.Select(i => new 
        {
            ID = i.ID,
            Thumbnail = i.Thumbnail
        }
        .ToList()
    })
    .ToList();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM