开发者

How to write an NHibenerate query that queries children?

I need to write an NHibernate query that w开发者_如何学Pythonill place a restriction that accesses the children in a one to many relationship.

For example, I have a customer object that has property that is a list of addresses. I need to find all customers who have an address in a given city.

Also, I am writing this query in such a way that I will also be adding other restrictions to the customer itself, such as status, name, etc. So, I can't write the query purely from the address perspective.

Any ideas on how to accomplish this?


You can use the Criteria api, with a "nested" criteria on the Adresses property of your Customer object :

var result = session
    .CreateCriteria(typeof(Customer))
        .CreateCriteria("Adresses")
        .Add( Restriction.Eq("City", "NY") )
    .ToList<Customer>();

If you need to query on name, you can go like this :

var customerCriteria = session
    .CreateCriteria(typeof(Customer));

customerCriteria.Add( Restrictions.Like("Name", "John", MatchMode.Exact) );

customerCriteria.CreateCriteria("Adresses")
    .Add( Restriction.Eq("City", "NY") );

var result = customerCriteria.ToList<Customer>();
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜