Domanda

Si prega di consultare il seguente esempio, che è una versione molto semplificata del mio codice:

Dim Criteria = Session.CreateCriteria(Of Person)()
Criteria.SetProjection(Projections.Property("Car"))
return Criteria.List(Of Car)()

Questo funziona perfettamente, però NHibernate 3.1 crea due query per recuperare i risultati. Qualcosa di simile:

SELECT CarId FROM Person WHERE blababla

e quindi per ogni riga:

SELECT color, brand, wheels FROM Car WHERE CarId = ?

Questa non è molto efficiente così ho provato:

Criteria.CreateAlias("Car", "Car")
Criteria.SetFetchMode("Car", NHibernate.FetchMode.Join)

Il che non fa nulla. Come posso forzare NHibernate per fare un join sulla prima query, così finisco con un'andata e ritorno al server MySQL?

È stato utile?

Soluzione 2

I found a workaround using a subquery. This will work, but I think this still would be more efficient using a join so my original question still stands. My workaround:

var cars = s.CreateCriteria<Cars>()
    .Add(Subqueries.PropertyIn("Id",
        DetachedCriteria.For<Person>()
            .Add(Restrictions.Eq("Name","MyName"))
            .SetProjection(Projections.Property("Car.Id"))
        ))
    .List<Cars>();

Altri suggerimenti

When you do Projections.Property("Car") and Car is a many-to-one reference, it just becomes an alias for Projections.Property("Car.Id"). If you want to get the actual Car object you have 2 options:

Option 1: Specify all properties of a car in the projection list.

Criteria.CreateAlias("Car", "Car")
Criteria.SetFetchMode("Car", NHibernate.FetchMode.Join)
Criteria.SetProjection(Projections.Projectionist() _
           .Add(Projections.Property("Car.Color")) _
           .Add(Projections.Property("Car.Brand")))

If wheels is another entity list then it gets a lot trickier.

Option 2: Specify the query from the Car standpoint

Criteria.CreateCriteria(Of Car)()
Criteria.CreateAlias("Person", "person")
... //specify your criteria

There's also an additional option of not using projections and getting the Person object with a fetched Car object

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top