2

我有这样的:如何使用计数相关联的实体凡在实体框架

 var queryResult = (from post in posts 
        select new 
           { 
            post, 
            post.Author, 
            post.Tags, 
            post.Categories, 
            Count = post.Comments.Count() 
           }).ToList(); 

但我需要的东西是这样的:

 var queryResult = (from post in posts 
        select new 
           { 
            post, 
            post.Author, 
            post.Tags, 
            post.Categories, 
            Count = post.Comments.Where(x=>x.IsPublic).Count() 
           }).ToList(); 

但post.Comments是一个ICollection的

回答

0

如何关于使用Enumerable.Cast<T>()这样?

var queryResult = (from post in posts 
        select new 
           { 
            post, 
            post.Author, 
            post.Tags, 
            post.Categories, 
            Count = post.Comments.Cast<Comment>() 
                 .Where(x=>x.IsPublic).Count() 
           }).ToList(); 

假设post.Comments类型为Comment

+0

问题不是类型本身。实体框架不支持: 无法创建类型为'PostComment'的常量值。在此上下文中仅支持基本类型(如Int32,String和Guid)。 – 2011-02-17 01:43:22

+1

您可能希望将异常消息包含在问题文章中。此外,检查出http://stackoverflow.com/questions/879411/entity-framework-unable-to-create-a-constant-value-of-type-closure-type – 2011-02-17 01:48:44

0

尝试:

var queryResult = (from post in context.Posts 
       select new 
          { 
           post, 
           post.Author, 
           post.Tags, 
           post.Categories, 
           Count = context.Comments.Where(c => c.Post == post).Where(c => IsPublic == 1).Count() 
          }).ToList(); 
0

我写它作为LukLed没有,但要使它工作,我将使用后的实体的PK:

var queryResult = (from post in context.Posts 
       select new 
          { 
           post, 
           post.Author, 
           post.Tags, 
           post.Categories, 
           Count = context.Comments.Where(c => c.Post.Id == post.Id && c.IsPublic == 1).Count() 
          }).ToList(); 

或者,如果forign键通过关联暴露Post.Id可能只是被写成帖子ID我相信它会更有效率。