2010-04-22 23 views
8

我使用NHibernate,並正嘗試找出如何編寫一個查詢,該searchs所有的名字我的實體, 並列出結果。舉一個簡單的例子,我有以下幾個對象;NHibernate的查詢在多個表

public class Cat { 
public string name {get; set;} 
} 

public class Dog { 
    public string name {get; set;} 
} 

public class Owner { 
    public string firstname {get; set;} 
    public string lastname {get; set;} 
} 

Eventaully我想創建一個查詢,例如說,它並返回所有的寵物主人含「泰德」的名稱,或寵物使用含有「泰德」的名稱。

這是我要執行的SQL的一個例子:

SELECT TOP 10 d.*, c.*, o.* FROM owners AS o 
INNER JOIN dogs AS d ON o.id = d.ownerId 
INNER JOIN cats AS c ON o.id = c.ownerId 
WHERE o.lastname like '%ted%' 
OR o.firstname like '%ted%' 
OR c.name like '%ted%' 
OR d.name like '%ted%' 

當我使用它的標準是這樣做的:

var criteria = session.CreateCriteria<Owner>() 
     .Add(
     Restrictions.Disjunction() 
      .Add(Restrictions.Like("FirstName", keyword, MatchMode.Anywhere)) 
      .Add(Restrictions.Like("LastName", keyword, MatchMode.Anywhere)) 
     ) 
     .CreateCriteria("Dog").Add(Restrictions.Like("Name", keyword, MatchMode.Anywhere)) 
     .CreateCriteria("Cat").Add(Restrictions.Like("Name", keyword, MatchMode.Anywhere)); 
     return criteria.List<Owner>(); 

中生成以下查詢:

SELECT TOP 10 d.*, c.*, o.* FROM owners AS o 
    INNER JOIN dogs AS d ON o.id = d.ownerId 
    INNER JOIN cats AS c ON o.id = c.ownerId 
    WHERE o.lastname like '%ted%' 
    OR o.firstname like '%ted%' 
    AND d.name like '%ted%' 
    AND c.name like '%ted%' 

如何調整我的查詢,以便.CreateCriteria(「Dog」)和.CreateCriteria(「Cat」)生成一個OR而不是t他和?

感謝您的幫助。

回答

5

試試這個,它可能工作。

var criteria = session.CreateCriteria<Owner>() 
      .CreateAlias("Dog", "d") 
      .CreateAlias("Cat", "c") 
      .Add(
      Restrictions.Disjunction() 
       .Add(Restrictions.Like("FirstName", keyword, MatchMode.Anywhere)) 
       .Add(Restrictions.Like("LastName", keyword, MatchMode.Anywhere)) 
       .Add(Restrictions.Like("c.Name", keyword, MatchMode.Anywhere)) 
       .Add(Restrictions.Like("d.Name", keyword, MatchMode.Anywhere)) 
      ); 
+0

謝謝,似乎這樣做。我在這裏找到了一篇文章:http://mattthr.blogspot.com/2010/02/quey-across-join-in-nhibernate.html,並試圖嘗試 – 2010-04-23 10:20:26

2

你需要使用Expression.Or(標準1,criteria2)兩個標準

這裏更多組合:http://devlicio.us/blogs/derik_whittaker/archive/2009/04/21/creating-a-nested-or-statement-with-nhibernate-using-the-criteria-convention.aspx

嗯,我想這應該是這樣的(借用BuggyDigger的代碼位)

var criteria = session.CreateCriteria<Owner>() 
    .CreateAlias("Dog", "d") 
    .CreateAlias("Cat", "c") 
    .Add(Expression.Or(Expression.Like("c.Name", keyword, MatchMode.Anywhere) 
      , Expression.Like("d.Name", keyword, MatchMode.Anywhere)) 
     ); 

但我沒有注意到你想要或所有東西。在這種情況下,像BuggyDigger所說的那樣,將這些標準加入到分解中,可能是一種可行的方法。

+0

謝謝你的回覆Alex,你能否提供一個例子。我想你做了什麼,但我得到「無法的ICriteria轉換爲Icriterion」 – 2010-04-23 07:51:17

+0

在我的崗位澄清,但因爲我讀的問題錯了,它可能並不重要;) – AlexCuse 2010-04-23 13:23:30

+0

感謝您的幫助反正!現在就完美了! ;) – 2010-04-23 14:08:42