views:

46

answers:

2

I have an nHibernate querie issue that looks quite straight forward, but I can't seem to get my head around it!

I am creating some simple example classes to illustrate my problem:

public class Car {
    public int Id { get; set; }
    public IList<Interior> InteriorParts { get; set; }
}

public class Interior {
    public int Id { get; set; }
    public InteriorProducer Producer { get; set; }
}

public class InteriorProducer {
    public int Id { get; set; }
}

Now to the query: I have the id of the InteriorProducer, but need to get a list of Cars where the interior have been produced by the interior producer.

So in a simple, pseudo SQL, it looks something like this:

select cars
where car.InteriorParts.Producer.Id = Id

I have a really hard time getting my head around this to create an nHibernate query.

Any Ideas?

Thanks

+2  A: 
var cars = session
    .CreateCriteria<Car>()
    .CreateAlias("InteriorParts", "parts")
    .CreateAlias("parts.Producer", "producer")
    .Add(Expression.Eq("producer.Id", id))
    .List();

Depending on your case you might also want to filter duplicate cars that will be fetched due to the SQL joins:

.SetResultTransformer(Transformers.DistinctRootEntity)
Darin Dimitrov
+2  A: 

and in hql...

var query = session.CreateQuery
   ("select c from Cars c where c.InteriorParts.Producer.Id = :pid");
query.SetInt32("pid", producerId);
IList<Car> cars = query.List<Car>();
Jaguar
thx moo, forgot to tag it properly
Jaguar