假设我有类似目标:
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; }
}
现在,我要选择租用一辆汽车的所有使用者。
这样做只会是 The。
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
我正试图通过这一询问在NHibernate的QueryOver工作。
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
因此,在答复之后,我不得不作几处改动(大多数是小的辛迪加错误),认为我把工作文本放在了后面。
由于我的使用人没有直接提及汽车,我不得不修改其他内容来这样做。
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>();
以上一点,我使用的是过时的标准,因此,我改写了第二组法典,如:
DetachedCriteria dc = QueryOver.Of<Car>()
.WithSubquery.WhereProperty(car => car.Id).In(subQuery)
.TransformUsing(new NHibernate.Transform.DistinctRootEntityResultTransformer())
.DetachedCriteria
;