如何计算嵌套集合/代码中的项目第一个实体框架

时间:2011-11-27 18:59:02

标签: linq entity-framework-4.1 ef-code-first

我已经按照以下定义定义了CodeFirst集合。

对于任何给定的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; }
}

1 个答案:

答案 0 :(得分: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。