mosguy1844
mosguy1844

Reputation: 23

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.

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. 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>();

Upvotes: 2

Views: 2007

Answers (1)

Radim K&#246;hler
Radim K&#246;hler

Reputation: 123901

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...

Upvotes: 1

Related Questions