2012-02-19 52 views
1

我想根據2個id來檢索一個對象。criteria + nhibernate +基於2個id的回退對象

這是正確的標準嗎?

var notes = session 
       .CreateCriteria(typeof(Note)) 
       .Add(Restrictions.Eq("Product", productId)) 
       .Add(Restrictions.Eq("User", userId)) 
       .List<Note>(); 

此查詢是否獲取屬於用戶和產品的註釋?

並執行此標準:

var comments = session 
       .CreateCriteria(typeof(Comment)) 
       .Add(Restrictions.Eq("Product", productId)) 
       .Add(Restrictions.Eq("IsOwnComment", 0)) 
       .List<Comment>(); 
      return comments; 

回報,其中布爾值是0產品的意見嗎?

我做對了嗎?

BR

回答

2
var notes = session 
       .CreateCriteria(typeof(Note)) 
       .Add(Restrictions.Eq("Product", productId)) 
       .Add(Restrictions.Eq("User", userId)) 
       .List<Note>(); 

這不會像這樣工作。您需要提供產品和用戶的完整關聯路徑實體。你可以做的是使用特殊的id屬性:

var notes = session 
       .CreateCriteria(typeof(Note)) 
       .Add(Restrictions.Eq("Product.id", productId)) 
       .Add(Restrictions.Eq("User.id", userId)) 
       .List<Note>(); 

對於第二個例子中,使用Restrictions.IsNull("IsOwnComment")

+0

感謝您的幫助! – Thommie 2012-02-19 20:00:04

+0

當然,沒問題... – 2012-02-21 11:52:11

1

當您使用添加標準的表達沒有確定或者或表達它們之間的NHibernate將使用和默認讓你寫的性判據將等同於這些HQL查詢:

"from Note note where note.Product=:productId and note.User=:userId" 

"from Comment comment where comment.Product=:productId and comment.IsOwnComment=0" 

只有一件事應該注意:如果產品和用戶是多對一的關係,這些查詢將不起作用,您應該使用Product.Id和User.Id作爲屬性名稱

+0

如何在hql和標準之間進行轉換?是的,他們是多對一的..我怎麼確定他們的標準利卡和或或?你能讓我成爲一個例子,所以我明白,所以我可以制定更多的標準.. – Thommie 2012-02-19 20:04:58

+0

是這樣的? .Add(Restrictions.Eq(「Product」,productId)&& Restrictions.Eq(「User」,userId)) – Thommie 2012-02-19 20:07:06

+0

Add.Restrictions.Eq(「Product.Id」,productId) – Beatles1692 2012-02-19 21:00:43