2010-11-09 93 views
1

我有一个用户类,有很多帖子,后期类有一个用户属性。我的问题是,在存储库中获取用户,我打电话到Post存储库以获取所有用户帖子。在获取Post的存储库中,我还调用User存储库来获取海报。我如何使用POCO和存储库模式处理这样的事情?LINQ to SQL:循环查询

这是模型。

public class User { 
    public IEnumerable<Post> Posts {get; set;} 
    /* Other properties here */ 
} 

public class Post { 
    public User Poster {get; set;} 
    /* Other properties here */ 
} 

库代码:

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() 
         }; 
} 

如果我到任何一个电话,我得到Object not instantiated

PS的错误。我刚刚删除了一个针对错误问题的问题,所以我提出了一个新的问题来正确定义问题。

回答

0

你就错了;)和忽略LINQ到SQLS能力正确地生成加入相关实体:

http://msdn.microsoft.com/en-us/library/bb399393.aspx

http://msdn.microsoft.com/en-us/library/system.data.linq.dataloadoptions.loadwith.aspx


EF例子:

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

好文档: http://msdn.microsoft.com/en-us/library/bb896272.aspx

+0

我的问题是我使用POCO。如果我在Post查询中查询用户,我有5个属性来重写从实体映射到POCO的这种转换。反之亦然。 – 2010-11-09 02:58:07

+1

是的,这是L2SQL的问题,你需要从POCO的左到右克隆。实体框架FTW。 – RPM1984 2010-11-09 05:26:30

+0

@ RPM1984你能写一个答案,并给出一些例子或解决方案吗?在EF中。 – 2010-11-09 11:58:26

0

想要在DataContext的存储库模式之上实现自己的存储库模式吗?你希望你的仓库能够毫不费力地在数据库类型和域类型之间进行转换?

看起来你会失去对数据库访问发生时的控制权,通过返回延迟查询。

由于查询被延期,您的上下文将暂停一段时间,所以您可能不会在您的工作单元之后进行处理。你正在设置陈旧的数据。

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

详细说明'TranslateUserWithPostsToDomain()'是什么?将生成的实体转换为我的自定义书写实体是否更简单? – 2010-11-10 01:03:35

+0

这是你写的一个方法。 – 2010-11-10 13:09:07