0

I have these entities:

public class Post {
    public virtual int Id { get; set; }
    public virtual ICollection<Tag> Tags { get; set; }
    public virtual ICollection<Comment> Comments { get; set; }
}

public class Tag {
    public virtual int Id { get; set; }
    public virtual ICollection<Post> Posts { get; set; }
}

public class Comment {
    public virtual int Id { get; set; }
    public virtual Post Post { get; set; }
}

I want to load a Post by it's related Tags and related Comments's count by LINQ. I use this:

var posts = session
    .Query<Post>()
    .OrderBy(t => t.Id)
    .Select(t => new {
        Post = t,
        CommentsCount = t.Comments.Count(),
        Tags = t.Tags        
    }).ToList();

Do you think it is enough? or do you have any suggestion that may be better than my code? thanks.

Mike Mooney
  • 11,729
  • 3
  • 36
  • 42
amiry jd
  • 27,021
  • 30
  • 116
  • 215

1 Answers1

1

This highly depends on your mapping and what you want to do with the fetched result. Imho eager loading Tags would speed up performance (Select N+1) if you want to access the tags list (assuming that the tags are mapped as lazy).

var posts = session
    .Query<Post>()
    .Fetch(t => t.Tags)
    .OrderBy(t => t.Id)
    .Select(t => new {
        Post = t,
        CommentsCount = t.Comments.Count(),
        Tags = t.Tags        
    }).ToList();

http://ayende.com/blog/1328/combating-the-select-n-1-problem-in-nhibernate

Andreas
  • 5,251
  • 30
  • 43