2010-08-01 33 views
7
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>(); 

但城市,地區或國家可爲空。我如何將數據庫中的null與nhibernate進行比較?nhibernate限制條件.Eq和null

回答

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

例如爲:

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

另見HHH-2951

+0

另一種方式來寫它: 回報(價值== NULL)? Restrictions.IsNull(property):Restrictions.Eq(property,value); – 2011-11-24 11:27:37

5
session.CreateCriteria<Advertisements>() 
     .Add(Expression.Or(
       Expression.Eq("AdvName", "Cool Advertisement"), 
       Expression.IsNull("AdvName")) 
     ).List<Advertisements>();