您可以使用投影來做到這一點。在3.X使用QueryOver API它會是這個樣子(子查詢你的情況會有所不同,但不能太離譜):
var subquery = DetachedCriteria.For<ToppingUse> ("t")
.Add (Restrictions.EqProperty ("t.Pizza.Id", "p.Id"))
.SetProjection (Projections.Count ("Id"));
Pizza p = null;
var toppedPizzas = session.QueryOver<Pizza>(() => p)
.Select(Projections.Property(() => p.Id)
, Projections.Property(() => p.Sauce)
, Projections.Property(() => p.Crust)
, Projections.Alias(Projections.SubQuery(subquery), "ToppingCount"))
.List<object[]>(); //then you need to handle mapping on your own somehow (look into ResultTransformers if needed)
這相當於下列標準:
var subquery = DetachedCriteria.For<ToppingUse> ("t")
.Add (Restrictions.EqProperty ("t.Pizza.Id", "p.Id"))
.SetProjection (Projections.Count ("Id"));
var toppedPizzas = session.CreateCriteria<Pizza>("p")
.SetProjection(Projections.Property("p.Id")
, Projections.Property("p.Sauce")
, Projections.Property("p.Crust")
, Projections.Alias(Projections.SubQuery(subquery), "ToppingCount"))
.List<object[]>();//then you need to handle mapping on your own somehow (look into ResultTransformers if needed)
您只需確保在子查詢和外部查詢中使用相同的別名。
A BIG謝謝你!它工作完美,我真的很高興你幫助我與這一個:) –
很高興它的工作。我試着回來換一個更具代表性的子查詢。 – AlexCuse