我有 2 个这样的对象
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; }
}
我正在尝试编写一个 linq to nhibernate 查询来选择一个包含具有特定 ID 的子项的父项。 return x => x.Children.Contains
不起作用。我也试过这个。
return x => (from y in x.Children where y.ChildId.Equals(childId) select y).Count() > 0
我的流利映射是这样的
HasManyToMany<Child>(x => x.Children)
.Table("ParentsChildren")
.ParentKeyColumn("ParentId")
.ChildKeyColumn("ChildId");
如何通过 ID 找到包含子项的父项?
最佳答案
您使用的是哪个 NHibernate 版本?
如果您正在使用新的 NHibernate linq 库,那么我认为您可以执行以下操作:
var parent = session.Query<Parent>()
.Where(p => p.Children.Any(c => c.ChildId == childId))
.FirstOrDefault();
在旧版本中,您必须使用 .Linq<T>()
而不是 .Query<T>()
:
var parent = session.Linq<Parent>()
.Where(p => p.Children.Any(c => c.ChildId == childId))
.FirstOrDefault();
我不记得旧的 NHibernate linq 库是否已经支持这些类型的查询。
关于c# - Linq to nhibernate - 其中集合包含具有 id 的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4739129/