2010-11-09 171 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