Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nhibernate Restrictions.Eq and null

Tags:

nhibernate

Advertisements advertisements = NHibernateSession.CreateCriteria(typeof(Advertisements))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Price.ToString(), price))
                    .Add(Restrictions.Eq(AdvertisementsProperties.HollidayDuration.ToString(), hollidayDuration))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Name.ToString(), name))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Description.ToString(), description))
                    //.Add(Restrictions.Eq(AdvertisementsProperties.DepartureDate.ToString(), departureDate))
                    .Add(Restrictions.Eq(AdvertisementsProperties.City.ToString(), city))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Area.ToString(), area))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Country.ToString(), country))
                    .Add(Restrictions.Eq(AdvertisementsProperties.Agency.ToString(), agency))
                    .UniqueResult<Advertisements>();

but city, area or country can be null. How can i compare null in DB with nhibernate?

like image 294
senzacionale Avatar asked Aug 01 '10 07:08

senzacionale


2 Answers

public AbstractCriterion EqOrNull(string property, object value) {
    if (value == null)
        return Restrictions.IsNull(property);
    return Restrictions.Eq(property, value);
}

E.g.:

session.CreateCriteria<Advertisements>()
       .Add(EqOrNull(AdvertisementsProperties.City.ToString(), city));

Also see HHH-2951

like image 185
Mauricio Scheffer Avatar answered Oct 14 '22 17:10

Mauricio Scheffer


session.CreateCriteria<Advertisements>()
       .Add(Expression.Or(
                 Expression.Eq("AdvName", "Cool Advertisement"),
                 Expression.IsNull("AdvName"))
        ).List<Advertisements>();
like image 28
gillyb Avatar answered Oct 14 '22 17:10

gillyb