Question

I have a Domain Model for Countries and States that looks like the following(see below).

I want to (with the Crieteria API or HQL) fetch all States for a specific country. I receive as a parameter the CountryCode.

From what I understand in NHibernate, I must load the country and then issue the call to my second repository with the "Country Object" to be able to make an Expression.Eq() in my crieria. Is there any way to fetch all States for a specific Country and therefore, use a single query ? I just want to do a simple SQL inner join and and then add a constraint on the country code.

I'm sure it has something to do with projections but the only examples I've found are for a single model and show how to use aggreate function which is not what I intend to do.

Thank you very much for your help !

My current repository call looks like this :

 public IList<Model.StateProvinces> LoadStateProvincesForAutocomplete(string partialName, string countryCode)
 {
    CountryRepository countryRepo = new CountryRepository();
    Model.Country currentCountry = countryRepo.Get(countryCode);


    return
    _session.CreateCriteria<Model.StateProvince>()
        .Add(Expression.Eq("Country", currentCountry))
        .Add(Expression.Like("Name", partialName, MatchMode.Anywhere))
        .List<Model.StateProvince>();
 }

And my models are defined as follow :

public class Country
{
   public virtual int Id { get; set; }
   public virtual string Code { get; set; }
   public virtual string NameEn { get; set; }
   public virtual string NameFr { get; set; }
   public virtual List<Model.StateProvince> StateProvinces { get; set; }
}

public class StateProvince
{
        public virtual Country Country { get; set; }
        public virtual int Id { get; set; }
        public virtual string Code { get; set; }
        public virtual string NameEn { get; set; }
        public virtual string NameFr { get; set; }
 }
Was it helpful?

Solution

Should be pretty simple if you use the lambda extensions to ICriteria:

session.CreateCriteria<StateProvince>().Add(s=>s.Country.NameEn == "United States").List();

This ought to add the proper join and equality constraint, as long as the two entities' relationship is properly mapped in your HBMs.

Also, try Linq2NH with the NHibernate.Linq namespace:

session.Linq<StateProvince>().Where(s=>s.Country.NameEn == "United States").ToList();

I'm setting up Linq queries as you read this that go a couple layers deeper; no sweat at all.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top