我有一个对象" Property"有孩子的" Notes"和"附件"。 我想带回整个" Property",所有相关的" Notes"但只有一个字段来自"附件"。我不想带回整个"附件"因为它包含巨大的base64图像。如果我需要这些,我可以通过" AttachmentId"来获取它们。问题是在使用Lambda Include时如何缩小字段范围。以下不起作用。我真的不想创建一个冗长的LINQ语句
var property = await _context.Property
.Include(x => x.Notes)
.Include(x => x.Attachments.Select(y => new PropertyAttachment
{
PropertyId = y.PropertyId,
AttachmentId = y.AttachmentId,
Type = y.Type,
Title = y.Title,
Content = ""
}).ToList())
.SingleOrDefaultAsync(x => x.PropertyId == key);
答案 0 :(得分:1)
使用选择和匿名类型,您可以这样尝试
var property = _context.Property.Select(x => new
{ Property = x,
HMOUnits = x.HMOUnits,
Notes = x.Notes,
AttachmendId = new { Id = x.Attachments.Select(z=> z.AttachmentId) }
})
.SingleOrDefaultAsync(x =>
x.Property.ID == key &&
(RestrictUser(User) ? x.Property.Tenancies.Any(y => y.Assignments.Any(z => z.Tenant.UserID == Convert.ToInt32(User.Identity.Name))) : true)
);