I have the following model.
Subscription Packages PackageWidgets Widgets
------------ -------- -------------- -------
ID ID < PackageID ID
PackageID > WidgetID >
I am using Entity Framework 4 and a Subscription has a relationship to Package. And Package has a relationship to a list of Widgets.
Using Linq, I am trying to get a listing of all Widgets and if they are included in the current subscription. Perhaps it’s due to my SQL background that I’m just not seeing the query in Linq. SQL would involve a SELECT from Widgets, with a LEFT JOIN through a subselect of Subscriptions, Packages and PackageWidgets based on the passed in SubscriptionID.
The output I would expect would be something like WidgetID,IsIncluded such that I would have all Widget IDs and a boolean indicating the inclusion status.
I cannot seem to even get something remotely close to working in order to show what I’ve done so far.
Can anyone provide me with some insights on how to accomplish my query?
Update:
Here is what I’ve come close with, but it still doesn’t work. Maybe it will help illustrate what I am trying to accomplish though:
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
}
Update #2
Thanks to the accepted answer, this is what I ended up going with – which does what I need:
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)
}
Thanks for the assist!
One way to approach it is breaking it up, so something like:
Or doing it based on the ID’s instead of the objects, something like:
Keep in mind that you can always do the query yourself if you want – in EF4 you can just call ExecuteStoreQuery with your own SQL