c# - 如何获取所有元素以及它们是否已分配?

标签 c# linq entity-framework

我有以下模型。

Subscription    Packages    PackageWidgets    Widgets
------------    --------    --------------    -------
ID              ID        < PackageID         ID
PackageID    >              WidgetID       >

我正在使用 Entity Framework 4,并且 SubscriptionPackage 有关系。 PackageWidgets 列表有关系。

使用 Linq,我正在尝试获取 所有 Widgets 的列表,以及它们是否包含在当前订阅中。也许是由于我的 SQL 背景,我只是没有在 Linq 中看到查询。 SQL 将涉及来自 Widgets 的 SELECT,以及基于传入的 SubscriptionID 通过子选择 Subscriptions、Packages 和 PackageWidgets 的 LEFT JOIN。

我期望的输出类似于 WidgetID,IsIncluded 这样我将拥有所有 Widget ID 和一个指示包含状态的 bool 值。

为了展示我到目前为止所做的事情,我什至无法得到一些离工作很近的东西。

谁能提供一些有关如何完成查询的见解?

更新: 这是我已经接近的,但它仍然不起作用。也许它会帮助说明我正在努力完成的事情:

from subscription in Subscriptions
where subscription.ID == 3
let subWidgets = subscription.Package.Widgets
from widget in Widgets
join subWidget in subWidgets on widget.ID equals subWidget.ID into joined
from list in joined.DefaultIfEmpty()
select new {
    ID = widget.ID
    ,Selected = subWidget.ID != null
}

更新#2 多亏了公认的答案,这就是我最终要做的——它满足了我的需要:

from widget in Widgets
from subWidgets in
  from subscription in Subscriptions
  where subscription.ID == 3
  select subscription.Package.Widgets
orderby widget.ID
select new { 
    Name = widget.WidgetName,
  Available = subWidgets.Contains(widget)
}

感谢您的协助!

最佳答案

处理它的一种方法是将其分解,例如:

var widgetsInSubscription =
    from subscription in Subscriptions
    where subscription.ID == 3
    from widget in subscription.Package.Widgets
    select widget;

var allWidgets =
    from widget in Widgets
    select new
    {
        widget.ID,
        Selected = widgetsInSubscription.Contains(widget),
    };

或者根据 ID 而不是对象来做,比如:

var widgetIDsInSubscription =
    from subscription in Subscriptions
    where subscription.ID == 3
    from widget in subscription.Package.Widgets
    select widget.ID;

var allWidgets =
    from widget in Widgets
    select new
    {
        widget.ID,
        Selected = widgetIDsInSubscription .Contains(widget.ID),
    };

请记住,如果需要,您始终可以自己进行查询 - 在 EF4 中,您只需调用 ExecuteStoreQuery使用你自己的 SQL

关于c# - 如何获取所有元素以及它们是否已分配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526409/

相关文章:

C# 使用 linq 连接两个 Collection<string> 并获得 Collection<string> 结果

c# - 如何使无窗口/命令行应用程序返回但继续在后台执行?

c# - LINQ to XML .Count() 方法返回 HEX?如何将其转换为 Int?

c# - Enumerable.Single 的错误执行?

c# - 获取所有模型类型

c# - 如何在单独的项目中配置 Entity Framework ?

c# - Entity Framework/code first/table-per-type inheritance——实现派生类和具体类之间的一对多关联

C# - 在标签/元素之外读取 XML

c# - 无法将类型 'System.Collections.Generic.List<AnonymousType#1>' 隐式转换为 'System.Collections.Generic.List<FirstApp.Model.TeamDetails>

c# - 数组克隆字节 10-40?