NHibernate 多个带有 in 子句的子查询

NHibernate multiple subqueries with in clause

我有一个正在工作的 SQL 查询:

SELECT * FROM truck t
WHERE t.currentlocationdbid IN (SELECT dbid FROM location WHERE name = 'Los Angeles')
OR t.nextdestinationdbid IN (SELECT dbid FROM location WHERE name = 'Chicago' OR name = 'New York');

我想用 NHibernate 编写这个。当然,它可以为每个实体多次访问 DB,但我想让它成为一次。查看带有 this, this or this 等分离查询的示例,但 none 对我有用。也尝试使用别名和标准来做到这一点。

数十次尝试之一:

var subQuery1 = QueryOver.Of<LocationEntity>().Where(l => l.Name == LocationNameEnum.LA);
var subQuery2 = QueryOver.Of<LocationEntity>().Where(l => l.Name == LocationNameEnum.CHG || l.Name == LocationNameEnum.NY);

var poc = session.QueryOver<TruckEntity>()
                 .WithSubquery.WhereProperty(t => t.CurrentLocation).In(subQuery1)
                 .WithSubquery.WhereProperty(t => t.NextDestination).In(subQuery2)
                 .List<TruckEntity>();

提前感谢您的任何建议。

您几乎答对了,您只是缺少 SQL 中 or.Where(Restrictions.Disjunction()...)

根据您的代码(假设您在 LocationEntity 中有一个 属性 Id):

// get IDs to look for in CurrentLocation
var subQuery1 = QueryOver.Of<LocationEntity>()
    .Where(l => l.Name == LocationNameEnum.LA)
    .Select(x => x.Id);

// get IDs to look for in NextDestination
var subQuery2 = QueryOver.Of<LocationEntity>()
    .Where(l => l.Name == LocationNameEnum.CHG || l.Name == LocationNameEnum.NY)
    .Select(x => x.Id);

var poc = session.QueryOver<TruckEntity>()
    .Where(Restrictions.Disjunction() // this takes care of the OR
        .Add(Subqueries.WhereProperty<TruckEntity>(x => x.CurrentLocation.Id).In(subQuery1))
        .Add(Subqueries.WhereProperty<TruckEntity>(x => x.NextDestination.Id).In(subQuery2))
    )
    .List<TruckEntity>();