I have a User class that has many posts and the post class has a user property. My problem is that in the repository to get User, I make a call to the Post repository to get all the user posts. In the repository to get Post, I also make a call to the User repository to get the poster. How do I handle something like this using POCO and repository pattern?
Here is the model.
public class User {
public IEnumerable<Post> Posts {get; set;}
/* Other properties here */
}
public class Post {
public User Poster {get; set;}
/* Other properties here */
}
repository code:
public IQueryable<User> GetUsers()
{
return from u in context.Users
select new User
{
/*Other properties */
Posts = postRepo.GetPostsByUserId(u.UserId)
};
}
public IQueryable<Post> GetPostsByUserId(int userId)
{
//Well, I actually call GetPosts().Where(p => p.PosterId == userId);
return from p in context.Posts
select new Post
{
/*Other properties */
Poster = userRepo.GetUsers().Where(u => u.UserId == p.PosterId).SingleOrDefault()
};
}
If i make a call to either one, I get the error of Object not instantiated
PS. I just deleted a question targeting the wrong problem, so I made a new question defining the problem correctly.
Your doing it wrong 😉 and ignoring Linq to Sqls ability to correctly generate joins for related entities:
http://msdn.microsoft.com/en-us/library/bb399393.aspx
http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx
EF Example:
Good documentation:
http://msdn.microsoft.com/en-us/library/bb896272.aspx