NHibernate跨多个表查询

时间:2010-04-22 15:04:18

标签: sql nhibernate hql icriteria

我正在使用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我想创建一个查询,比如说,并且返回所有宠物主人,其名称包含“ted”,OR宠物的名称包含“ted”。

以下是我想要执行的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%' 

当我使用Criteria这样做时:

    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而不是AND?

感谢您的帮助。

2 个答案:

答案 0 :(得分: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))
            );

答案 1 :(得分:2)

您需要使用Expression.Or(criteria1,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所示,将这些标准添加到析取中可能是要走的路。