简体   繁体   English

跨多对多和多对多关系的Nhibernate析取(“ OR”)查询

[英]Nhibernate Disjunction (“OR”) Query Across Many-To-One and Many-To-Many Relationships

This question is close to but not the same as the one here: NHibernate Query across multiple tables 这个问题与这里的问题很接近,但并不相同: 跨多个表的NHibernate查询

Basically, my question is given the following model, how would I query to find out if the current dog has the name "foo" or a past dog has the name "foo" (disjunction). 基本上,我的问题给出以下模型,我将如何查询以查找当前狗的名称为“ foo”还是过去的狗的名称为“ foo”(析取)。 Essentially I have a Many-To-One relationship for CurrentDog and a Many-To-Many relationship for PastDogs. 本质上,我对CurrentDog具有多对一关系,对于PastDogs具有多对多关系。

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

public class Owner {
    public string firstname {get; set;}
    public string lastname {get; set;}
    public Dog CurrentDog {get; set;}
    public Dog[] PastDogs {get; set;}
}

I'd guess the SQL should look something like this: 我猜想SQL应该看起来像这样:

    SELECT o.* FROM owners AS o
    INNER JOIN dogs AS cd ON o.current_dog_id = cd.id
    INNER JOIN owner_past_dog_maps AS pd ON o.id = pd.owner_id
    INNER JOIN dogs AS d ON pd.dog_id = d.id
    WHERE d.name = 'foo' 
    OR cd.name = 'foo'

Hope that makes sense... I'll try clarify it if anyone asks. 希望有道理...如果有人问,我会尽力澄清。

I've try to solve it using QueryOver and alias 我尝试使用QueryOver和别名解决它

Owner myOwner = null;
Dog myCurrentDog = null; 
Dog myPastDogs = null;

var sax = _HibSession.QueryOver<Owner>(() => myOwner)
                .JoinAlias(() => myOwner.CurrentDog, () => myCurrentDog, JoinType.InnerJoin)
                .JoinAlias(() => myOwner.PastDogs, () => myPastDogs , JoinType.InnerJoin)
                .Where(Restrictions.Disjunction()
                    .Add(Restrictions.EqProperty(myCurrentDog.Name,"foo"))
                    .Add(Restrictions.EqProperty(myPastDogs.Name,"foo"))                    
                )                                            
                .List<Owner>();

I hope it's helpful! 希望对您有所帮助!

I guess I should have started off that I was new to NHibernate. 我想我应该刚开始是NHibernate的新手。 What I didn't understand was the aliasing going on in NHibernate and that you're creating aliases not for the tables but for the relationships and the property names. 我不了解的是NHibernate中的别名,您不是在为表而是为关系和属性名创建别名。 Behold, the solution that will return all the owners who have or had a dog name foo: 看哪,将返回所有拥有或拥有狗名foo的所有者的解决方案:

    var output = Session.CreateCriteria<Owner>()
        .CreateAlias("CurrentDog", "cd")
        .CreateAlias("PastDogs", "pd")
        .Add
        (
            Restrictions.Disjunction()
            .Add(Restrictions.Eq("cd.Name", "foo"))
            .Add(Restrictions.Eq("pd.Name", "foo"))
        )
        .List<Owner>();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM