tags:

views:

131

answers:

2

Let's say I have a list of Boxes and in a box you can have multiple items.

  • Box (id)
  • Items (id, boxId)

I'm trying to build a linq to entity query that can return all the boxes that contains ALL specified items.

List<Box> FindBoxContainingAllSpecifiedItems(List<int> itemIds)
{
    var q = from box in ctx.Boxes
            where ???
}

Thanks for the help

+4  A: 

It depends on the implementation of boxes. But lets for the moment say it has a property Items with the type IEnumerable<int>. In that case you could use the Intersect extension method to see if the items are all accounted for

var q = from box in ctx.Boxes
        where box.Items.Intersect(itemIds).Count() == itemIds.Count;
JaredPar
ahh thanks I will try this out
pdiddy
What if I don't have thie IEnumerable<int> but IEnumerable<Items> ...?
pdiddy
@pdiddy, what is the API for Items?
JaredPar
I'll try to explain. It's a little bit more complex. I have a location entity, a box entity and item entity. A location can contain one or more boxes and in one boxe you can have one or more items. My requirement is to be able to find location containing SOME specified items. Also to be able to find location containing ALL specified items. Here is the description of my entity: Location (id, navigationProperty to Collection of Box entity), Boxes (id, navigationProperty to Location, navigation to Collection of Item entity), Items(id, navigationProperty to Box). linq-entity is really not trivial
pdiddy
I have found a way to make it work. I had to build a linq query to gets all the items and then I could use intersect
pdiddy
A: 

Here is what I have found thanks to JaredPar contribution.

List<Location> FindLocationContainingAllItems(List<int> itemIds)
{
    var itemQuery = from item in ctx.Items
                    select item;

    // Workaround the Where In Clause (http://social.msdn.microsoft.com/Forums/en/adodotnetentityframework/thread/095745fe-dcf0-4142-b684-b7e4a1ab59f0)
    itemQuery = itemQuery.Where(BuildContainExpression<Items, int>(i=> i.Id, itemIds));

    int itemCount = itemIds.Count();

    var locQuery = from loc in ctx.Locations
                   from box in loc.Boxes
                   where (from items in box.Items select items).Intersect(itemQuery).Count == itemCount
                   select loc;

    return locQuery.ToList();

 }
pdiddy
let me know what you guys think of this solution
pdiddy