Linq to nhibernate - Where collection contains object with id
Asked Answered
S

1

4

I have 2 objects like this

public class Child
{
    public virtual int ChildId { get; set; }
}

public class Parent
{
    public virtual int ParentId { get; set; }

    public virtual IList<Child> Children { get; set; }
}

I am trying to write a linq to nhibernate query to select a parent where it contains a child with a specific id. return x => x.Children.Contains does not work. I also tried this.

return x => (from y in x.Children where y.ChildId.Equals(childId) select y).Count() > 0

My fluent mapping looks like this

HasManyToMany<Child>(x => x.Children)
            .Table("ParentsChildren")
            .ParentKeyColumn("ParentId")
            .ChildKeyColumn("ChildId");

How can I find the parent that contains a child by id?

Sinew answered 19/1, 2011 at 18:25 Comment(1)
I ended up making a composite object consisting of the parent object and the child id. Then, I mapped it to the ParentsChildren table and use that object in my query. Then I use linq to select the parent(s) from the composite objects returned by my query.Sinew
U
7

Which NHibernate version are you using?

If you are using the new NHibernate linq library, then I think you van do something like:

var parent = session.Query<Parent>()
    .Where(p => p.Children.Any(c => c.ChildId == childId))
    .FirstOrDefault();

In older versions you had to use .Linq<T>() instead of .Query<T>():

var parent = session.Linq<Parent>()
    .Where(p => p.Children.Any(c => c.ChildId == childId))
    .FirstOrDefault();

I can't remember if the older NHibernate linq library already supported these kind of queries.

Undertone answered 19/1, 2011 at 19:16 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.