5

En How To Count Associated Entities using Where In Entity Framework me sale esta consultaCómo usar Include y Anonymous Type en la misma consulta en Entity Framework?

Pero cuando accedo a QueryResult [0] .post.Category o QueryResult [0] .post.Tags Siempre es vacía, porque no estoy usando incluyen.

Incluir no trabajan con la proyección, como se dice en el último elemento Microsoft aquí: http://msdn.microsoft.com/en-us/library/bb896317.aspx

var queryResult = (from post in posts 
          join comment in comments.Where(x=> x.IsPublic) on post.Id equals comment.Post.Id into g 
        select new 
           { 
            post, 
            post.Author, 
            post.Tags, 
            post.Categories, 
            Count = g.Count() 
           }) 

¿Cómo puedo obtener el recuento en la misma consulta, e Incluir relación a las etiquetas y categorías?

¿Por qué la relación de reparación de EF no funciona aquí?

+0

que debería funcionar bien. Tal vez hay algo mal con sus clases modelo. ¿Puedes agregar el código EF First Code a esta pregunta? – LukLed

+0

Hice algunas investigaciones, y este es el comportamiento esperado. La reparación de la relación no funciona para Many-To-Many –

+0

Pregunta similar con una respuesta funcional: http://stackoverflow.com/questions/7167547/linq-to-entities-include-anonymous-type-issue – Dunc

Respuesta

1

Esto se puede hacer con 2 consultas:

var posts = 
    from post in context.Posts.Include(p => p.Author).Include(p => p.Tags).Include(p => p.Categories) 
    where post.Comments.Any(c => c.IsPublic) 
    select post; 
var counts = 
    from post in context.Posts 
    where post.Comments.Any(c => c.IsPublic) 
    select new { PostId = post.Id, Count = post.Comments.Count() }; 
var countDictionary = counts.ToDictionary(e => e.PostId, e => e.Count); 

foreach (var item in posts) 
{ 
    System.Console.WriteLine("PostId {0}, TagCount {1}, PublicCommentCount {2}", item.Id, item.Tags.Count, countDictionary[item.Id]); 
} 

Por Diego Vega: http://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/c0bae1c1-08b2-44cb-ac29-68a6518d87bd

Cuestiones relacionadas