【问题标题】:Join vs Navigation property for sub lists in Entity Framework实体框架中子列表的加入与导航属性
【发布时间】:2013-05-24 17:35:39
【问题描述】:

我有一个这样的sql语句:

DECLARE @destinations table(destinationId int)
INSERT INTO @destinations
VALUES (414),(416)

SELECT *
FROM GroupOrder grp (NOLOCK)
          JOIN DestinationGroupItem destItem (NOLOCK)
                    ON destItem.GroupOrderId = grp.GroupOrderId
          JOIN @destinations dests
                    ON destItem.DestinationId = dests.destinationId
WHERE OrderId = 5662

我正在使用实体框架,我很难将此查询输入 Linq。 (我写上面的查询的唯一原因是帮助我概念化我在寻找什么。)

我有一个 GroupOrder 实体的 IQueryable 和一个整数列表,它们是我的目的地。

看了这个之后,我意识到我可能只需要做两个连接(比如我的 SQL 查询)就可以得到我想要的。

但是这样做似乎有点奇怪,因为 GroupOrder 对象上已经有一个 DestinationGroupItem 对象列表。

当我有 GroupOrder 的 IQueryable 列表时,我有点困惑如何使用 GroupOrder 上的 Navigation 属性。

另外,如果可能的话,我想一次性访问数据库。 (我想我可以做几个foreach 循环来完成这项工作,但它的效率不如对数据库的单个 IQueryable 运行。)

注意:与查询 linq 语法相比,我更喜欢流畅的 linq 语法。但是乞丐不能挑剔,所以我会尽我所能。

【问题讨论】:

  • 你试过Linqer它执行从SQL到LINQ的转换(不像LINQPad它执行LINQ到SQL)

标签: c# .net linq entity-framework navigation-properties


【解决方案1】:

如果您已经将 DestinationGroupItem 作为导航属性,那么您已经拥有等效的 SQL-JOIN - example。使用Include 加载相关实体。使用 List 的 Contains 扩展方法查看所需的 DestinationId(s) 是否命中:

var destinations = new List<int> { 414, 416 };
var query = from order in GroupOrder.Include(o => o.DestinationGroupItem) // this is the join via the navigation property
            where order.OrderId == 5662 && destinations.Contain(order.DestinationGroupItem.DestinationId)
            select order;
// OR
var query = dataContext.GroupOrder
            .Include(o => o.DestinationGroupItem)
            .Where(order => order.OrderId == 5662 && destinations.Contain(order.DestinationGroupItem.DestinationId));

【讨论】:

  • 我需要为 DestinationGroupItem 列表中的每个项目创建一个单独的对象。
  • 我在我的答案中增强了代码。我忘记了目的地
  • 一个简单的问题。如果将.Where() 放在.Include() 之前,这不是更有效吗?
  • @Celdor 老实说......我不知道。我找不到有关此问题的任何文档,也没有对其进行测试。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2016-03-29
  • 2016-05-29
相关资源
最近更新 更多