这个问题接近但与此处的问题不同: NHibernate Query across multiple tables
基本上,我的问题是给出以下模型,我将如何查询当前的狗是否具有名称“foo”或过去的狗是否具有名称“foo”(分离)。 基本上我对于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;}
}
我猜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'
希望有意义......如果有人问,我会尝试澄清它。
答案 0 :(得分:4)
我尝试使用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>();
我希望它有用!
答案 1 :(得分:0)
我想我应该开始说我是NHibernate的新手。我不明白的是NHibernate中的别名,你创建的别名不是为了表,而是为了关系和属性名。看哪,这个解决方案将归还所有拥有或拥有狗名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>();