2

假设我有类似的对象:

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
    ;
4

1 回答 1

2
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>();
于 2012-04-25T14:15:48.427 回答