gpt4 book ai didi

nhibernate queryover join 与子查询以获取聚合列

转载 作者:行者123 更新时间:2023-12-04 03:30:25 27 4
gpt4 key购买 nike

我已经搜索了几个小时如何做到这一点,但似乎无法找到任何帮助我的东西。

这是数据库模型:

enter image description here

这是我尝试运行的 SQL 查询:

SELECT b.*, a.Assignments FROM Branch b LEFT JOIN (
SELECT b.BranchID , COUNT(ab.BranchID) AS Assignments
FROM Branch b LEFT JOIN AssignmentBranch ab ON b.BranchID = ab.BranchID
GROUP BY b.BranchID
) a ON b.BranchID = a.BranchID

所以,基本上,我想返回一个分支列表和一个代表该分支分配数量的新列。

分支模型
public class Branch : IEntity<int>
{
public virtual int ID
{
get;
set;
}

public virtual string Name { get; set; }

public virtual IList<AssignmentBranch> Assignments { get; set; }

}

分配分支模型
public class AssignmentBranch : IEntity<int>
{
public virtual int ID
{
get;
set;
}

public virtual DateTime AssignedOn { get; set; }

public virtual Branch Branch { get; set; }
}

这是我的 NHibernate 配置:
<class name="Branch" table="Branch">

<id name="ID" column="BranchID">
<generator class="identity"></generator>
</id>

<property name="Name"/>

<bag name="Assignments" cascade="none" inverse="true">
<key column="BranchID"/>
<one-to-many class="AssignmentBranch"/>
</bag>
 <class name="AssignmentBranch" table="AssignmentBranch">

<id name="ID" column="AssignmentBranchID">
<generator class="identity"></generator>
</id>

<property name="AssignedOn" />
<property name="FromDate" />
<property name="ToDate" />

<many-to-one name="Assignment" column="AssignmentID" />
<many-to-one name="Branch" column="BranchID" />

我已经尝试了多种方法,但我似乎无法找到一种使用 QueryOver 加入子查询的方法。

我试过这样:
 // aliases
Branch branch = null; AssignmentBranch assignment = null;

var subquery = QueryOver.Of<Branch>(() => branch)
.Where(() => branch.Project.ID == projectID)
.JoinQueryOver<AssignmentBranch>(() => branch.Assignments, ()=> assignment,
NHibernate.SqlCommand.JoinType.LeftOuterJoin)
.SelectList(list => list
.SelectGroup(x=>x.ID)
.SelectCount(()=>assignment.ID)
);

var query = session.QueryOver<Branch>(()=>branch)
.JoinAlias(???) // how can I join with a sub-query?
.TransformUsing(Transformers.AliasToBean<BranchAssignments>())
.List<BranchAssignments>();

有人可以帮我吗?它不必完全与子连接一起使用,也许我缺少另一个更好的解决方案......

谢谢,
科斯敏

最佳答案

在这里阅读了数百个类似的问题后,我找到了答案:相关的子查询。像这样:

// aliases
Branch branch = null; AssignmentBranch assignment = null;

var subquery = QueryOver.Of<AssignmentBranch>(() => assignment)
.Where(() => assignment.Branch.ID == branch.ID)
.ToRowCountQuery();

var query = session.QueryOver<Branch>(() => branch)
.Where(() => branch.Project.ID == projectID)
.SelectList
(
list => list
.Select(b => b.ID)
.Select(b => b.Name)
.SelectSubQuery(subquery)
)
.TransformUsing(Transformers.AliasToBean<BranchAssignments>())
.List<BranchAssignments>();

我得到答案的类似问题是 this one .

关于nhibernate queryover join 与子查询以获取聚合列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7153819/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com