Is there a more logically place to put that method ?
IMO, yes. I wouldn't have a specific method like that unless you require a list of posts a lot of time. I would Eager Load the Posts on demand. (More on this, below)
Should I put it in PostRepository ?
Sorta. LoadPosts(User user)
is a PostRepository specific login, IMO. BUT - it's a very specific method .. which means that sooner-or-later you're PostRepository will get very busy with lots of specific methods. We usually have a generic repository which allows Expressions to come in. That way, you don't need to create lots of specific methods. You can have one method that excepts expressions and retrieves your various requests.
for example.
IQueryable<Post> Find(Expression<Func<Post, bool>> predicate,
string[] includeAssociations);
Then you can use it to eager load what you need.
eg. Get all posts for a particular user.
var posts = _postRepostitory
.Find(x => x.UserId = userId, new [] { "User" } )
.ToList();
or the flip side, For a user, get me all their posts...
var user = _userRepository
.Find(x => x.UserId = userId, new [] { "Posts" } )
.ToList();
If you need some help with the code inside the Find
method, just ask .. but it's pretty trivial.
The idea is this (in order, which is cruical)
- the expression is just applied to the
Post
entity inside the hidden context inside the postRespository
instance.
- Finally, you
Include
for each association that is required, last.
Nothing is hardcoded. It's all defined by the coder when they call the Find method :) One method to rule them all.
NOTE: Of course, i actually have 4 - one with no arguments .. all the way down to the one i've shown, with 4 args.
Something like CountPosts(int userId) ?
(Untested, pseduo code .. thinking off the top of my head)
var count = _postRepostiory
.Find(x => x.UserId = userId, new [] { "Posts" })
.Select(x => x.Posts).Count;
Should I offer an overload on my LoadMethod. Example : Load(bool loadPosts)
Nope. not needed now.
Is there a way that if I write myUser.Posts.Count() Posts is loaded automatically instead of being null ?
Yep, if you follow my suggestions above.
var user = _userRepository
.Find(x => x.UserId = userId, new [] { "Posts" })
.SingleOrDefault();
var postCount = user == null || user.Posts == null ? 0 : user.Posts.Count;
Go nuts and program away, padawan!!