Come ottenere il valore da una sottoquery in NHibernate? `
-
26-10-2019 - |
Domanda
Al momento sto costruendo un forum in cui ho bisogno per emettere il numero di messaggi in un thread.
- ID
- Nome
- MessageCount
In SQL pianura sarebbe simile a questo, ma non riesco a trovare alcuna documentazione su come fare il inline select
.
SELECT
t.ID,
t.Name
(SELECT COUNT(*) FROM Messages m WHERE m.ThreadID = t.ID)
FROM Threads t
Ho trovato solo esempi su come limitare il gruppo di risultati utilizzando query indipendenti, non come selezionare i valori effettivi da loro.
Come faccio a fare un inline-selezionare con NHibernate? Io preferisco usare ICriteria sopra HQL.
EDIT:. Ho semplificato la mia domanda troppo complicata per rendere più facile la comprensione
Soluzione
È possibile utilizzare le proiezioni per fare questo. Utilizzando l'API QueryOver in 3.X che sarebbe simile a questa (subquery nel tuo caso sarà diverso, ma non troppo lontano):
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)
questo si traduce con i seguenti criteri:
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)
Hai solo bisogno di assicurarsi di utilizzare gli stessi alias all'interno del vostro subquery e query esterna.