开发者

Linq to nhibernate - Where collection contains object with id

开发者 https://www.devze.com 2023-02-05 07:44 出处:网络
I have 2 objects like this public class Child { public virtual int ChildId { get; set; } } public class Parent

I have 2 objects like this

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

public class Parent
{
    public开发者_StackOverflow中文版 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?


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.

0

精彩评论

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

关注公众号