【问题标题】:How to select an entity based on it's association, like a WHERE IN query in raw SQL如何根据实体的关联选择实体,例如原始 SQL 中的 WHERE IN 查询
【发布时间】:2011-11-17 21:25:45
【问题描述】:

假设我有一个像这样的实体:

Parent

它有一个孩子的集合:

Parent.Children

我正在尝试获取 children.Id 在列表中的所有父母。

Session.QueryOver<Parent>( () => parentAlias)
.JoinAlias( () => pareintAlias.Children, () => childrenAlias)
.WHereResitrictionOn(childrenAlias.Id).IsIn(childrenList)
.List<Parent>();

但上面的不起作用,它说索引引用超出范围或类似的东西。

更新

我的桌子:

父母 -Id

儿童 -parentId

我的实体有一个 HasMany 集合链接到 Children 表。

所以查询应该是这样的:

SELECT * 
FROM Parents p
    INNER JOIN Children c ON (c.parentID = p.id)
WHERE c.id in (SELECT id from Children WHERE id in (....) )

我有一份孩子名单:

List<Children> childrenList;

【问题讨论】:

  • 如果你给我们一些我们可以转换的sql,你可能会变得更好。
  • @Ash 更新了我想要的表格布局和查询。
  • Doh' 没有看到这是一个 nHibernate 问题。在 linq 中,如果您使用相当简单的逻辑来确定子列表,那么它类似于: var selectedParents = from c in Context.Children where c.Proper1 == DesiredProperty1 Select c.Parent;
  • @PeterLaCombJr。即使他使用 LINQ,这也不会执行 OP 的查询,他想要包含

标签: c# nhibernate


【解决方案1】:

更新:需要指定&lt;Child&gt;

使用 QueryOver

var results = Session.QueryOver<Parent>()
    .JoinQueryOver<Child>(parent => parent.Children)
        .WHereResitrictionOn(child => child.Id).IsIn(childrenList)
    .List<Parent>();

或使用 LINQ

var results = (from parent in Session.Query<Parent>()
               from child in parent.Children
               where child.Id.IsIn(childrenList)
               select parent).List();

【讨论】:

  • 在您的 QueryOver 示例中,我需要创建别名吗? child.Id 似乎无法解析。
  • 通常 JoinQueryOver 应该更改所有后续调用子类型的类型
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-16
  • 2020-05-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多