2011-11-27 82 views
3

我已經定義瞭如下定義的CodeFirst集合。如何計算嵌套集合/ codefirst中的項目EntityFramework

對於任何給定的EmailOwnerId,我想統計存在EmailDetailAttachments記錄的數量,而不實際下載所有圖像本身。

我知道我可以這樣做

var emailsToView = (from data in db.EmailDetails.Include("EmailDetailAttachments") 
         where data.EmailAccount.EmailOwnerId = 999 
         select data).ToList(); 
int cnt = 0;  
foreach (var email in emailsToView) 
{ 
    cnt += email.EmailDetailAttachments.Count(); 
} 

但這意味着我已經下載圖像的所有字節從我的遙遠的服務器。

任何建議,將不勝感激。

public class EmailDetail 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 
    public int EmailOwnerId {get;set;} 

    public virtual ICollection<ImageDetail> EmailDetailAttachments { get; set; } 
    .. 
} 

public class ImageDetail 
{ 
    [Key] 
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] 
    public int Id { get; set; } 

    [MaxLengthAttribute(256)] 
    public string FileName { get; set; } 

    [MaxLengthAttribute(256)] 
    public string ContentMimeType { get; set; } 

    public byte[] ImageDataBytes { get; set; } 
    public DateTime ImageCreation { get; set; } 
} 

回答

4

引擎應該能夠將其更新爲COUNT(*)語句。

var emailsToView = (from data in db.EmailDetails // no Include 
        where data.EmailAccount.EmailOwnerId = 999 
        select new { 
         Detail = data, 
         Count=data.EmailDetailAttachments.Count() } 
        ).ToList(); 

但是你必須驗證這是否產生正確的(和更高效的)SQL。

+0

謝謝亨克,偉大的技術。我一定會在將來使用它。我沒有想到這一點。 –