问题
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