[英]NHibernate QueryOver .Left.JoinAlias with additional join criteria
[英]NHibernate Criteria to QueryOver
我仍在學習NHibernate,並且想知道是否有人可以幫助我將以下條件轉換為QueryOver
。
我認為我的基礎知識不高,但是查詢子集合並添加別名時我有點迷茫。 發布的條件查詢確實返回了預期的數據,但是我不確定我對條件格式的所有魔術字符串的適應程度如何。
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>();
編輯:我能夠使用以下QueryOver返回所需的結果。 我以為我會發布解決方案,以防其他人解決。 也歡迎您提供任何有關改進此代碼的建議。
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>();
它可能看起來像這樣:
// 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();
有關更多信息,請在這里深入了解:
注意:還檢查子查詢,因為查詢“集合”時這些子查詢要好得多。 只需搜索它們...並將它們用作子選擇WHERE parentId IN (SELECT parentId FROM ChildTable...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.