Question

I have a sql statement like this:

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

I am using entity framework and I am having a hard time getting this query into Linq. (The only reason I wrote the query above was to help me conceptualize what I was looking for.)

I have an IQueryable of GroupOrder entities and a List of integers that are my destinations.

After looking at this I realize that I can probably just do two joins (like my SQL query) and get to what I want.

But it seems a bit odd to do that because a GroupOrder object already has a list of DestinationGroupItem objects on it.

I am a bit confused how to use the Navigation property on the GroupOrder when I have an IQueryable listing of GroupOrders.

Also, if possible, I would like to do this in one trip to the database. (I think I could do a few foreach loops to get this done, but it would not be as efficient as a single IQueryable run to the database.)

NOTE: I prefer fluent linq syntax over the query linq syntax. But beggars can't be choosers so I will take whatever I can get.

Was it helpful?

Solution

If you already have the DestinationGroupItem as a Navigation-property, then you already have your SQL-JOIN equivalent - example. Load the related entities with Include. Use List's Contains extension method to see if the desired DestinationId(s) is(are) hit:

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));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top