我有一个模型,其中包括可以具有附件的打孔,附件具有Id,Name和BinaryData的属性。
如果我这样做:
var result = context.PunchSet
.Where(p => p.PunchType == punchType && p.Project.Id == projectId)
.Include(c => c.Contractor)
.Include(c => c.ClearedBy)
.Include(c => c.CreatedBy)
.Include(a => a.Attachments)
由于附件可能既多又大,因此查询速度很慢。在这种情况下,我需要的是附件的ID和名称。所以我试过了:
var result = context.PunchSet
.Where(p => p.PunchType == punchType && p.Project.Id == projectId)
.Include(c => c.Contractor)
.Include(c => c.ClearedBy)
.Include(c => c.CreatedBy)
.Include(a => a.Attachments.Select(a2 => new Attachment() { Id=a2.Id, Name=a2.Name} );
但最终会出现这个错误:
Include路径表达式必须引用导航属性 在类型上定义。使用虚线路径进行参考导航 属性和集合导航的Select运算符 属性。参数名称:路径
不知道这意味着什么,我被困了好几个小时。如何在结果中包含部分权利?即不读二进制数据。
答案 0 :(得分:1)
您可以尝试在单个查询中选择所有需要的属性,然后将它们连接在一起。
db.PunchSet
.Include(x => x.Contractor)
// ... other includes of complete objects
// then select properties for partial include
.Select(x => new { obj = x, att = x.Attachments.Select(a => new { a.Id, a.Name }) })
// end of database query context
.AsEnumerable()
// join the results in memory
.Select(x =>
{
x.obj.Attachments = x.att.Select(a => new Attachment() { Id = a.Id, Name = a.Name }).ToList();
return x.obj;
});
答案 1 :(得分:0)
您可以尝试如下所示。
var result = from p in context.PunchSet
where (p.PunchType == punchType && p.Project.Id == projectId)
select new {
p,
Contractor=p.Contractor,
ClearedBy =p.ClearedBy,
CreatedBy=p.CreatedBy,
Attachments= from a in p.Attachments
select new {
Id= a.Id,
Name =a.Name,
},
};
var result2 = result.AsEnumerable()
.Select(c => c.p);
之后你可以按照自己的意愿进行迭代:)
foreach(var r in result2 )
{
foreach(var a in r.Attachments)
{
//your code;
}
}