2010-04-22 46 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