Linq - 如何在没有'join'关键字的情况下构建此查询?

时间:2011-02-09 13:59:11

标签: linq linq-to-sql

我有以下部分Linq查询:

var query = from ri in RouteInstance
        join rir in RouteInstanceRules on ri.RouteInstanceID equals rir.RouteInstanceID
        join rl in RoutingLocation on rir.RoutingLocationID equals rl.RoutingLocationID
        join rlh in RoutingLocationHistory on rl.RoutingLocationID equals rlh.RoutingLocationID
        where rlh.RouteTakenTime >= new System.DateTime(2011,2,4) && rlh.RouteTakenTime <= new System.DateTime(2011,2,5)

There is a 1:M relationship between RouteInstance and RouteInstanceRules
There is a 1:M relationship between RouteInstanceRules and RoutingLocation
There is a 1:M relationship between RoutingLocation and RoutingLocationHistory

由于这些关系是使用FK强制执行的,因此对于L2S是已知的,因此我应该能够在不使用'join'关键字的情况下构造此查询。但是,我很难过如何去做。

感谢。

3 个答案:

答案 0 :(得分:2)

你想要RouteInstances吗?如果是这样的话:

var query = DataContext.RoutingLocationHistory
           .Where(rlh => rlh.RouteTakenTime >= new System.DateTime(2011,2,4) 
                        && rlh.RouteTakenTime <= new System.DateTime(2011,2,5))
           .Select(rlh => rlh.RoutingLocation.RouteInstanceRule.RouteInstance)
           .Distinct();

答案 1 :(得分:1)

我测试了像你这样的场景并获得了相同的结果 你可以选择很多没有加入的东西,比如:

var query = from ri in RouteInstance
            from rir in RouteInstanceRules 
            from   rl in        RoutingLocation
            from    rlh in RoutingLocationHistory 
             where    ri.RouteInstanceID ==    rir.RouteInstanceID &&
             rir.RoutingLocationID == rl.RoutingLocationID &&
             rl.RoutingLocationID == rlh.RoutingLocationID &&
             rlh.RouteTakenTime >= new System.DateTime(2011,2,4) && rlh.RouteTakenTime <= new System.DateTime(2011,2,5)

答案 2 :(得分:0)

检查dbml设计器中的关联。如果它注意到您的外键,它将自动创建关联。如果不是 - 您可以自己添加它们(即使外键不存在或未强制执行)。

通过查询关联属性,您可以隐藏关系详细信息。

query =
  from ri in dataContext.RouteInstances
  from rir in ri.RouteInstanceRules
  from rl in rir.RoutingLocations
  from rlh in rl.RoutingLocationHistories
  where rlh.RouteTakenTime >= new System.DateTime(2011,2,4)
    && rlh.RouteTakenTime <= new System.DateTime(2011,2,5)

如果你想要与Guillaume86的答案类似的结果,但没有明显的...那么这个子查询过滤器。

IQueryable<RouteInstance> query =
   from ri in dataContext.RouteInstances
   where ri.RouteInstanceRules
     .Any(rir => rir.RoutingLocations
       .Any(rl => rl.RoutingLocationHistories
         .Any(rlh => rlh.RouteTakenTime >= new System.DateTime(2011,2,4)
           && rlh.RouteTakenTime <= new System.DateTime(2011,2,5)
         )
       )
     )
   select ri;