开发者

LINQ to SQL: Circular queries

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()
       开发者_如何学Python               };
}

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:

var postsWithUsers = from p in context.Posts.Include("Users")
                     select new Post

Good documentation: http://msdn.microsoft.com/en-us/library/bb896272.aspx


You want to implement your own repository pattern, on top of the repository pattern that is DataContext? And you want your repository to effortlessly translate between the database types and domain types?

It looks like you're going to lose control over when database access occurs, by returning deferred queries.

Since the queries are deferred, your context will hang around for a while, so you're probably not disposing it after your unit of work. You're setting yourself up for stale data.

public Domain.User GetUserWithPostsById(int userId)
{
DataLoadOptions myOptions = new DataLoadOptions();
myOptions.LoadWith<User>(u => u.Posts);

User record = null;

using (MyDataContext myDC = new MyDataContext(connString))
{
  myDC.LoadOptions = myOptions;
  record = myDC.Users.Single(u => u.UserId = userId);
}

Domain.User result = TranslateUserWithPostsToDomain(record);
return result;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜