Nhibernate或查询

时间:2014-04-03 11:37:16

标签: nhibernate

public class PostUser
    {
        int UserId {get;set;}
        string Username {get;set;}
        string Email {get;set;}
        IList<Post> Posts {get;set;}
    }

   public class Post
   {
        int PostId {get;set;}
        int ThreadId {get;set;}
        int UserId {get;set;}
        string PageText {get;set;}
        string IPAddress {get;set;}
        PostUser Userposted {get;set;}
   }

我想进行如下查询:

Select * from POST JOIN POSTUSER ON POST.USERID = POSTUSER.USERID
WHERE POST.IPADDRESS LIKE '%86%' OR POST.PAGETEXT like '%something%' 
OR POSTUSER.EMAIL LIKE '%BLA%'

我的尝试是创造两个分离:

Disjunction postuserdisjunction = new Disjunction();
Disjunction postdisjunction = new Disjunction();

postuserdisjunction.Add(Restrictions.Like("email","%bla%"))
postdisjunction.Add(Restrictions.Like("IPAddress","%86%"))

IList<Post> p = _session.CreateCriteria<Post>()
                        .Add(postdisjunction)
                        .CreateCriteria("UserPosted")
                        .Add(postuserdisjunction)
                        .List<Post>();

但是这给我的结果SQL如下:

Select * from POST JOIN POSTUSER ON POST.USERID = POSTUSER.USERID
    WHERE (POST.IPADDRESS LIKE '%86%' OR POST.PAGETEXT like '%something%' ) AND POSTUSER.EMAIL LIKE '%BLA%'

请帮忙!

1 个答案:

答案 0 :(得分:0)

我们在这里可以做的是为每个表使用alias,并对两个析取使用OR表达式:

Disjunction postuserdisjunction = new Disjunction();
Disjunction postdisjunction = new Disjunction();

postuserdisjunction.Add(Restrictions.Like("up.email","%bla%"))  // alias "up" see below
postdisjunction.Add(Restrictions.Like("p.IPAddress","%86%"))    // alias "p"

IList<Post> p = _session.CreateCriteria<Post>("p")      // alias is "p" as above..
                    //.Add(postdisjunction)             // will use it later, not here
                    .CreateCriteria("UserPosted", "up") // alias is "up"
                    // here we can use both disjunctions with OR                   
                    .Add(
                       Restrictions.Or(
                          postdisjunction
                        , postuserdisjunction
                       )
                    )
                    .List<Post>();

编辑:如果我们不需要两个Disjunctions ......我们可以使用一个,和别名

Disjunction disjunction = new Disjunction();

disjunction.Add(Restrictions.Like("up.email","%bla%"))    // alias "up" see below
disjunction.Add(Restrictions.Like("p.IPAddress","%86%"))  // alias "p"

IList<Post> p = _session.CreateCriteria<Post>("p")      // alias is "p" as above..
                    .CreateCriteria("UserPosted", "up") // alias is "up"
                    // here we add just one set of OR
                    .Add(disjunction)
                    .List<Post>();

这更简单明了,但只有在不需要两个析取时才使用别名