Linq到nHibernate - 排除没有子元素的元素

时间:2012-07-25 09:11:12

标签: linq nhibernate linq-to-nhibernate

var locations = (from location in session.Query<Location>()                                     
             where 
                (location.MB_ID == 0 || location.MB_ID == null) &&
                (location.hide != "Y" || location.hide == null) &&
                (location.locationNameRaw != "" && location.locationNameRaw != null) &&
                ((location.isIPCapableText != "" && location.isIPCapableText != null) || (
                    (location.ISDNNumber1 != null && location.ISDNNumber1 != "") ||
                    (location.ISDNNumber2 != null && location.ISDNNumber2 != "") ||
                    (location.ISDNNumber3 != null && location.ISDNNumber3 != "") ||
                    (location.ISDNNumber4 != null && location.ISDNNumber4 != "") ||
                    (location.ISDNNumber5 != null && location.ISDNNumber5 != "") ||
                    (location.ISDNNumber6 != null && location.ISDNNumber6 != "")                                        
                ))
                && (location.privateRoom == "N" || location.privateRoom == "" || location.privateRoom != null)
                && (
                        from lll in session.Query<LocationLonLat>()                                             
                        where
                            location.locationID == lll.locationId
                        select lll.locationId
                    ).Any()
                && (location.LastUpdatedTime > lastUpdateTime)
                && location.LocationTimes.Count() > 0
               /*&& (
                        from lt in session.Query<LocationTimes>()
                        where
                            location.locationID == lt.LID
                        select lt.LID
                    ).Any()*/
                select location
                  )
                  .ToList();

Location(1)和LocationTimes(很多)之间存在关系,我只想返回至少有一个LocationTime记录的位置数据集。

我尝试了几件事......

当我添加这一行时:

&& location.LocationTimes.Count() > 0

或者如果我添加以下行:

  && (                      
     from lt in session.Query<LocationTimes>()
     where
    location.locationID == lt.LID
        select lt.LID
     ).Any()

基础连接已关闭:服务器已关闭预期保持活动状态的连接。

我怀疑这可能是因为数据集的大小或其他原因......

有更好的方法吗?就像“左外连接”或其他东西一样?

1 个答案:

答案 0 :(得分:1)

我认为一个简单的连接应该这样做。

from locationTime in Query<LocationTime>()
join location in Query<Location>() on locationTime.Location.LocationId equals location.LocationId
join locationLat in Query<LocationLat>() on location.LocationLat.LocationLatId equals locationLat.LocationLatId
where ...
select location;