我有一个以下工作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中写这个。当然,当它为每个实体多次访问数据库时,但我想让它成为一次旅行。看看像this,this或this这样的分离查询的示例,但没有一个对我有效。试图用别名和标准来做。
几十次尝试之一:
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中的.Where(Restrictions.Disjunction()...)
的or
。
基于您的代码(假设您在Id
中拥有属性LocationEntity
):
// 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>();