raberana
raberana

Reputation: 11816

NHibernate QueryOver (generic), tell query which properties of generic class it should use

it's my first time in NHibernate QueryOver and I'm trying to do it in a generic way. So far, this is what I have done..

//Find one only
public T Find(string propertyName1, string propertyName2, string value1, string value2)
{
    using (var session = sessionFactory.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        return session.QueryOver<T>().Where(d => propertyName1 == value1)
                                     .And(f => propertyName2 == value2).SingleOrDefault();
    }
}

I am not sure if this is right. What I am trying to do is, using a generic class, obtain an object saved in the database using two of its properties.

As you can see, I passed my property1 and property2. Using those two properties, I am wondering if I could query my database to find an object whose properties have the same values as value1 and value2 parameters.

Since it is generic, I need to find a way on how to tell my query which properties it should use as a criteria. What is the correct way to do this? Thanks guys.

Upvotes: 2

Views: 816

Answers (1)

Lodewijk
Lodewijk

Reputation: 2391

Perhaps you should be looking at Criteria Queries instead of QueryOver: http://docs.huihoo.com/hibernate/nhibernate-reference-1.2.0/querycriteria.html

public T Find(string propertyName1, string propertyName2, string value1, string value2)
{
    using (var session = sessionFactory.OpenSession())
    using (var transaction = session.BeginTransaction())
    {
        return session.CreateCriteria(typeof(T)).Add(Expression.Eq(propertyName1, value1 ))
                                 .Add(Expression.Eq(propertyName2, value2 )).SingleOrDefault();
    }
}

Upvotes: 4

Related Questions