Linq to nhibernate - Where collection contains object with id

偶尔善良 提交于 2019-12-10 16:38:57

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4739129/linq-to-nhibernate-where-collection-contains-object-with-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!