[英]NHibernate Custom IProjection that Runs a Sub-Query
說我有2張桌子,如下所示:
MainTable (
Id int,
Name varchar(100)
)
RelatedTable (
Id int,
Value int,
MainTableId int -- foreign key
)
MainTable
和RelatedTable
之間MainTable
一對多關系,因此RelatedTable.MainTableId
引用MainTable.Id
。
我想制作一個自定義的IProjection以如下方式使用:
sess.CreateCriteria<MainTable>()
.SetProjection(
Projections.ProjectionList()
.Add(Projections.Property("Id"))
.Add(Projections.Property("Name"))
.Add(new SumOfValuesProjection(/* arguments??? */))
)
.List();
生成以下SQL:
select
Id,
Name,
-- how to get this sub-query from IProjection?
(select sum(Value)
from RelatedTable
where RelatedTable.MainTableId = MainTable.Id) as SumOfValues
from MainTable
這只是我正在嘗試做的一個小例子。 就我而言,可能有數十個這些子查詢列。 它們都使用聚合函數,但可能不都使用sum()
。
我想創建一個自定義IProjection
但不確定從哪里開始。
任何幫助將不勝感激。
也許不是確切的答案,但也許是更直接的答案。 我想展示如何根據需要使用當前的NHibernate功能執行類似的SQL。
技巧不會在自定義IProjection
,而是在對現有功能強大的IProjection實現的調用中: Projections.SubQuery
var criteria = CreateCriteria<MainTable>("Main")
.SetProjection(
Projections.ProjectionList()
.Add(Projections.Property("Id"))
.Add(Projections.Property("Name"))
// here we go, let's profit from existing IProjection
.Add(Projections.SubQuery(
DetachedCriteria
.For<RelatedTable>("Related")
.SetProjection(Projections.Sum("Value"))
.Add(Restrictions.EqProperty("Main.Id", "Related.MainTableId")))
, "value")
)
...
;
如果這種方法還不夠,我建議觀察一下當前NHibernate代碼中如何實現此功能。 因為仍然-NHibernate是開源的...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.