加入后 nhibernate QueryOver select 一个 table

nhibernate QueryOver select one table after join

所以我在选择父实体时遇到问题,因为这也会 return 子实体。 目前我有以下实体:

public class Parent
{
    public virtual string KeyPart1 { get; set; }
    public virtual string KeyPart2 { get; set; }    
    public virtual string KeyPart3 { get; set; }
    public virtual string ParentProperty { get; set; }

    public virtual ISet<Child> Children { get; set; } = new HashSet<Child>();
}

public class Child
{
    public virtual string KeyPart1 { get; set; }
    public virtual string KeyPart2 { get; set; }    
    public virtual string KeyPart3 { get; set; }
    public virtual string KeyPart4 { get; set; }
    public virtual string ChildProperty { get; set; }
}

实际查询:

Parent parentAlias = null;
Child childAlias = null;
var query = Session.QueryOver(() => parentAlias)
    .Left.JoinAlias(x => x.Children, () => childAlias)
    .Where(whereClause);

这会生成与此非常相似的 sql 语句:

SELECT
    this_.KeyPart1 as KeyPart11_5_4_,
    this_.KeyPart2 as KeyPart22_5_4_,
    this_.KeyPart3 as KeyPart33_5_4_,
    this_.ParentProperty as ParentProperty4_5_4_,
    childalias1_.KeyPart1 as KeyPart11_6_6_,
    childalias1_.KeyPart2 as KeyPart22_6_6_,
    childalias1_.KeyPart3 as KeyPart33_6_6_,
    childalias1_.KeyPart4 as KeyPart44_6_6_,
    childalias1_.ChildProperty as ChildProperty5_6_6_,
FROM
    Parent this_ 
left outer join
    Child childalias1_ 
        on this_.KeyPart1=childalias1_.KeyPart1 
        and this_.KeyPart2=childalias1_.KeyPart2 
        and this_.KeyPart3=childalias1_.KeyPart3 
WHERE
    (SomeWhereClause)

请注意,这将 return 父表和子表。当

query.List()

是 运行,它将检索所有父项 + 每个父项的所有子项,从而在最终结果列表中创建重复的父项。我只想检索所有 Parents 或生成类似于以下内容的 sql 语句:

SELECT
    this_.KeyPart1 as KeyPart11_5_4_,
    this_.KeyPart2 as KeyPart22_5_4_,
    this_.KeyPart3 as KeyPart33_5_4_,
    this_.ParentProperty as ParentProperty4_5_4_,
FROM
    Parent this_ 
left outer join
    Child childalias1_ 
        on this_.KeyPart1=childalias1_.KeyPart1 
        and this_.KeyPart2=childalias1_.KeyPart2 
        and this_.KeyPart3=childalias1_.KeyPart3 
WHERE
    (SomeWhereClause)

有没有人对使用 nhibernate 的 QueryOver 执行此操作有任何提示 API?

一种方法是,使用 Transformers.DistinctRootEntity 例如:

var query = Session.QueryOver(() => parentAlias)
    .Left.JoinAlias(x => x.Children, () => childAlias)
    .Where(whereClause)

    // Here is the trick
    .TransformUsing(Transformers.DistinctRootEntity)

在这篇安德鲁·惠特克中查看更多内容post:

QueryOver Series - Part 4: Transforming

反之...

好吧,我不会去,其实我是去的,不要用这种方式。我真正证明的方法是:

  1. 从子项创建查询并加入父项(星型模式)
  2. 如果我们必须查询parent
    • 用于通过子项过滤 subselects
    • 批量加载子项使用映射设置batch-size

第一个很明显,因为我们查询的是星型模式,所以我们可以很方便地使用分页

第二个需要一些调整以按子过滤父:

  • Fetching Paginated Entity with Collection

为了有效加载子集合,我们可以从 batch-size 映射中获益。检查这些:

  • How to Eager Load Associations without duplication in NHibernate?
  • How to implement batch fetching with Fluent NHibernate when working with Oracle?