8

我正在使用 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”的所有宠物主人,或名称包含“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%' 

当我使用这样的标准进行操作时:

    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?

谢谢你的帮助。

4

2 回答 2

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))
            );
于 2010-04-23T10:12:19.327 回答
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))
        );

但我没有注意到你想要 OR 一切。在那种情况下,将这些标准添加到析取中,正如 BuggyDigger 所示,可能是要走的路。

于 2010-04-22T15:18:32.017 回答