2016-09-07 52 views
1

我有一個包含可以具有屬性Id,Name和BinaryData的附件的Punches的模型。在EF6中只包含部分實體包括

如果我這樣做:

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) 

查詢是慢如molassis因爲附件既可以是很多大。在這種情況下,我需要的是附件的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}); 

但與此錯誤結束:

The Include path expression must refer to a navigation property defined on the type. Use dotted paths for reference navigation properties and the Select operator for collection navigation properties. Parameter name: path

有不知道這意味着什麼,我一直堅持了幾個小時。如何在結果中包含部分實體?即不要讀取二進制數據。

+0

不能部分包括您可以迭代。但是,如果您只想閱讀而不更新,則可以在附件上省略附件並單獨加載附件。 – grek40

+1

我該如何在同一個查詢中做到這一點?我不想加載500拳,然後必須通過循環來獲取任何附件(如果有的話)。這將是一個好的舊SQL 5分鐘的工作。有時這個EF6的東西正在讓我。 – Paaland

+1

如果您需要加載部分相關的實體,則需要使用匿名類型或DTO來投影您的查詢​​。作爲異常解釋,你只能在'Include'擴展方法中引用導航屬性 – octavioccl

回答

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; 
    }); 
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; 
    } 
}