C# nhibernate查询在联接后选择一个表
因此,我在选择父实体时遇到问题,因为这也将返回子实体。 目前,我拥有以下实体:C# nhibernate查询在联接后选择一个表,c#,nhibernate,orm,queryover,C#,Nhibernate,Orm,Queryover,因此,我在选择父实体时遇到问题,因为这也将返回子实体。 目前,我拥有以下实体: public class Parent { public virtual string KeyPart1 { get; set; } public virtual string KeyPart2 { get; set; } public virtual string KeyPart3 { get; set; } public virtual string ParentPrope
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; }
}
这将生成与以下内容非常类似的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)
请注意,这将返回父表和子表。什么时候
query.List()
运行时,它将检索所有父项+每个父项的所有子项,并在最终结果列表中创建重复的父项。我只想检索所有父级或生成类似于以下内容的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来实现这一点有什么建议?一种方法是,使用
变压器。例如:
var query = Session.QueryOver(() => parentAlias)
.Left.JoinAlias(x => x.Children, () => childAlias)
.Where(whereClause)
// Here is the trick
.TransformUsing(Transformers.DistinctRootEntity)
请参阅安德鲁·惠特克的这篇文章:
另一方面
那我就不去了,其实我是去的,不用这个办法。我真正行之有效的方法是:
从子项和联接父项创建查询(星型架构)
如果我们要询问家长
- 用于通过子项进行筛选,请使用子项选择
- 要批量加载子项,请使用映射设置
批量大小
第一个是显而易见的,因为我们查询星型模式,所以我们可以很容易地使用分页
第二个需要进行一些调整,以便按子项筛选父项:
为了有效加载子集合,我们可以从批量大小映射中获益。检查以下各项:
感谢这一点,但它似乎创建了相同的查询,然后nhibernate在检索数据后过滤掉数据。
var query = Session.QueryOver(() => parentAlias)
.Left.JoinAlias(x => x.Children, () => childAlias)
.Where(whereClause)
// Here is the trick
.TransformUsing(Transformers.DistinctRootEntity)