开发者

NHibernate query looking for the related object's related object

I have an nHibernate query 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 ha开发者_运维技巧ve 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


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)


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>();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜