【问题标题】:QueryOver child collection from parentQueryOver 来自父级的子集合
【发布时间】:2013-04-16 22:46:14
【问题描述】:

我有这两个对象:

public class Parent
{
    public virtual int Poid { get; set; }
    public virtual IEnumerable<Child> Child { get; set; }
}

public class Child
{
    public virtual int Poid { get; set; }
    public virtual string Name {get; set;}    
}

我想使用 NHibernet QueryOver API 根据 Parent Id 和 Child Id 获取孩子,这意味着给我 Id = x 的孩子属于 Id = y 的父母。

我尝试过这样的事情:

return Session.QueryOver<Parent>().Where(p => p.Poid == y)
                .JoinQueryOver(p => p.WishesLists)
                .Where(c => c.Poid == x)
                .SingleOrDefault<Child>();

但我遇到了一个异常,无法将 Child 类型的对象转换为 Parent。

QueryOver 的正确形式如何以父实体开头但返回子实体?

【问题讨论】:

  • Child 是否有对父级的映射引用?也就是说,Child.Parent 可用吗?
  • 感谢您的回复,但不是没有,孩子不必知道父母。我用@jamie-ide 的答案解决了任何问题。

标签: nhibernate queryover


【解决方案1】:

我不知道 QueryOver 是否可以做到这一点,我在它上面工作了一段时间却没有任何结果。使用 LINQ 是可能的:

var child = session.Query<Parent>()
                   .Where(p => p.Poid == y)
                   .SelectMany(p => p.WishesLists)
                   .SingleOrDefault(c => c.Poid == x);

比起 QueryOver,我更喜欢 LINQ 语法。

另见NH-3176

【讨论】:

  • 感谢@Jamie 我尝试使用 QueryOver 也没有成功,但我意识到使用 LINQ 语法更容易,你的回答对我有帮助。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-20
  • 2021-12-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
相关资源
最近更新 更多