Assuming that I have objects similar to this:
public class User
{
public int UserId { get; set; }
public IList<UsersRentingLog> UsersRentLog { get; set; }
}
public class Car
{
public int CarId { get; set; }
public IList<UsersRentingLog> CarRentLog { get; set; }
}
public class UsersRentingLog
{
public Userid { get; set; }
public CarId { get; set; }
}
Now, I want to select all users who rented a particular car..
The sql for this would simply be
select c.*
from [User] u
inner join UsersRentingLog l on u.userid = l.UserId
inner join Car c on l.CarId = c.CarId
where u.userid = @UserId
I am trying to get this query to work in QueryOver, NHibernate, and so far, I have got this:
DetachedCriteria dc = QueryOver.of<User>()
.where(r => r.UserId == userId)
.JoinQueryOver<UsersRentingLog>(l => l.UsersRentLog)
.JoinQueryOver<Car>(c => c.Car)
.DetachedCriteria
;
This is selecting, as expected, every single property from all three joined tables, but I actually want to select only Cars.
How can I do this please?
Update on correct answer
So, after the answer, I had to make few modifications (mostly minor syntax errors) and thought I’d post the working version.
Because my user doesn’t have a direct reference to the car, I had to modify the alias to go with this
UsersRentingLog logAlias = null;
var subQuery = QueryOver.of<User>()
.Where(user => user.UserId == userId)
.JoinAlias(user => user.UsersRentLog, () => logAlias)
.subQuery.Select(Projections.Distinct(Projections.Property(() => logAlias.Car.Id)));
var query = _session.QueryOver<Car>();
query.WithSubquery.WhereProperty(car => car.Id).In(subQuery)
.TransformUsing(Transformers.DistinctRootEntity)
.List<Car>();
The above bit, I am using detached criteria, so I rewrote the second code block like so:
DetachedCriteria dc = QueryOver.Of<Car>()
.WithSubquery.WhereProperty(car => car.Id).In(subQuery)
.TransformUsing(new NHibernate.Transform.DistinctRootEntityResultTransformer())
.DetachedCriteria
;
1 Answer