1
criteriaCount.CreateCriteria(AdvertisementsProperties.City.ToString())
                .Add(Expression.Like(CitiesProperties.Name.ToString(), query, MatchMode.Anywhere))
                .Add(Expression.Like(CitiesProperties.SlovenianName.ToString(), query, MatchMode.Anywhere))
                .CreateCriteria(AdvertisementsProperties.Country.ToString())
                .Add(Expression.Like(CountriesProperties.Name.ToString(), query, MatchMode.Anywhere))
                .Add(Expression.Like(CountriesProperties.SlovenianName.ToString(), query, MatchMode.Anywhere));

This return "name like %foo% and slovenianName like %foo% and name like %foo% and slovenianName like %foo%"

but i would like to get "name like %foo% or slovenianName like %foo% or name like %foo% or slovenianName like %foo%"

i can use Expression.Disjunction() for OR but i have problem that i can not use CreateCriteria inside Expression.Disjunction(). Can someone tell me how can i use OR and CreateCriteria together?

Regards

James Gregory
  • 14,173
  • 2
  • 42
  • 60
senzacionale
  • 20,448
  • 67
  • 204
  • 316

2 Answers2

3

Use CreateAlias outside the Disjunction().

var result = session.CreateCriteria<Property>()
    .CreateAlias("Cities", "city")
    .CreateAlias("Countries", "country")
    .Add(Restrictions.Disjunction()
        .Add(Expression.Like("city.Name", query, MatchMode.Anywhere))
        .Add(Expression.Like("city.SlovenianNam", query, MatchMode.Anywhere))
        .Add(Expression.Like("country.Name", query, MatchMode.Anywhere))
        .Add(Expression.Like("country.SlovenianNam", query, MatchMode.Anywhere))
    ).List();

The corresponding entites are below. Hopefully they resemble yours.

class Property
{
    public virtual Guid Id { get; set; }
    public virtual IList<City> Cities { set; get; }
    public virtual IList<Country> Countries { set; get; }
}

class City
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string SlovenianNam{ get; set; }
}

class Country
{
    public virtual Guid Id { get; set; }
    public virtual string Name { get; set; }
    public virtual string SlovenianNam{ get; set; }
}
Lachlan Roche
  • 25,678
  • 5
  • 79
  • 77
1

Above example works good because both of othere classes are the constitutions of Property class.

If it is in this order it doesn't work.

class Property{ public virtual int Id { get; set; }
publice virtual string name { get; set;} Public virtual City city {get; set;} //many to one }

class City {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual country country { get; set; } //many to one }

class Country {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}