假设我有类似的对象:
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; }
}
现在,我想选择租用特定车辆的所有用户..
这个的SQL只是
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
我试图让这个查询在QueryOver,NHibernate中工作,到目前为止,我已经得到了这个:
DetachedCriteria dc = QueryOver.of<User>()
.where(r => r.UserId == userId)
.JoinQueryOver<UsersRentingLog>(l => l.UsersRentLog)
.JoinQueryOver<Car>(c => c.Car)
.DetachedCriteria
;
正如预期的那样,这是从所有三个连接表中选择每个属性,但实际上我只想选择Cars。 我该怎么办呢?
<小时/> 更新正确答案
所以,在答案之后,我不得不做一些修改(主要是次要的语法错误)并且认为我会发布工作版本。
因为我的用户没有直接引用汽车,所以我必须修改别名才能使用
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
;
答案 0 :(得分:1)
Car carAlias = null;
var subQuery = QueryOver.of<User>()
.Where(user => user.UserId == userId)
.JoinAlias(user => user.Cars, () => carAlias)
subQuery.Select(Projections.Distinct(
Projections.Property(() => carAlias.Id)));
var query = _session.QueryOver<Car>();
query.WithSubquery.WhereProperty(car => car.Id).In(subQuery);
.TransformUsing(Transformers.DistinctRootEntity)
.List<Car>();