[英]NHibernate Criteria to QueryOver
I am still learning NHibernate and am wondering if someone could help me translate the following criteria to its QueryOver
equivalent. 我仍在学习NHibernate,并且想知道是否有人可以帮助我将以下条件转换为
QueryOver
。
I think I have the basics down, but I am a little lost when querying the child collection and adding the alias. 我认为我的基础知识不高,但是查询子集合并添加别名时我有点迷茫。 The criteria query posted does return the expected data, but I'm not sure how comfortable I am with all the magic strings of the criteria format.
发布的条件查询确实返回了预期的数据,但是我不确定我对条件格式的所有魔术字符串的适应程度如何。
return Session.CreateCriteria<Person>()
.Add(Restrictions.Eq("FirstName", firstName))
.Add(Restrictions.Eq("LastName", lastName))
.CreateCriteria("PartyContactMechanisms")
.CreateAlias("ContactMechanism", "c")
.Add(Restrictions.Eq("c.ElectronicAddressString", emailAddress))
.UniqueResult<Person>();
Edit: I was able to return the desired result using the following QueryOver. 编辑:我能够使用以下QueryOver返回所需的结果。 I thought I'd post the solution in case it helps someone else out.
我以为我会发布解决方案,以防其他人解决。 Any suggestions on improving this code are welcome as well.
也欢迎您提供任何有关改进此代码的建议。
Person personAlias = null;
ElectronicAddress emailAlias = null;
PartyContactMechanism partyContactMechAlias = null;
return Session.QueryOver(() => personAlias)
.Where(p => p.FirstName == firstName)
.And(p => p.LastName == lastName)
.JoinQueryOver(() => personAlias.PartyContactMechanisms, () => partyContactMechAlias)
.JoinAlias(() => partyContactMechAlias.ContactMechanism, () => emailAlias)
.Where(() => emailAlias.ElectronicAddressString == emailAddress)
.SingleOrDefault<Person>();
It could look like this: 它可能看起来像这样:
// these are aliases, which we can/will use later,
// to have a fully-type access to all properties
Person person = null;
PartyContactMechanism partyContactMechanisms = null;
ContactMechanism contactMechanism = null;
// search params
var firstName = ..;
var lastName = ..;
var emailAddress = ..;
var query = session.QueryOver<Person>(() => person)
// the WHERE
.Where(() => person.FirstName == firstName)
// the And() is just more fluent eq of Where()
.And(() => person.LastName == lastName)
// this collection we will join as criteria
.JoinQueryOver(() => person.PartyContactMechanism, () => partyContactMechanisms)
// its property as alias
.JoinAlias(() => partyContactMechanisms.ContactMechanism, () => contactMechanism )
// final filter
.Where(() => contactMechanism.Code == emailAddress)
// just one result
.Take(1)
;
var uniqueResult = query
.List<Person>()
.SingleOrDefault();
for more information, please take a deep look here: 有关更多信息,请在这里深入了解:
NOTE: also check Subqueries, becuase these are much better when querying the "collections". 注意:还检查子查询,因为查询“集合”时这些子查询要好得多。 Just search for them... and use them as subselect
WHERE parentId IN (SELECT parentId FROM ChildTable...
只需搜索它们...并将它们用作子选择
WHERE parentId IN (SELECT parentId FROM ChildTable...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.