Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LINQ to SQL where collection contains collection

I have a problem :( I have a many-many table between two tables(1&2), via a mapping table(3):

(1)Trees / (2)Insects 

TreeID <- (3)TreeInsects -> InsectID   

And then a one to many relationship:

Trees.ID -> Leaves.TreeID

And I would like to perform a query which will give me all the Leaves for a collection of insects (via trees-insect mapping table).

E.g. I have List<Insects> and I want all Leaves that have an association with any of the Insects in the List via the Tree-Insects mapping table.

This seems like a simple task, but for some reason I'm having trouble doing this!!

The best I have: but the Single() makes it incorrect:

   from l in Leaves
            where (from i in Insects
                   select i.ID)
                  .Contains((from ti in l.Tree.TreeInsects
                             select ti.InsectID).Single())
            select l;
like image 665
Oliver Avatar asked Jun 09 '11 19:06

Oliver


2 Answers

(from i in insectsCollection
select from l in Leaves
       let treeInsectIDs = l.Tree.TreeInsects.Select(ti => ti.InsectID)
       where treeInsectIDs.Contains(i.ID)
       select l)
.SelectMany(l => l)
.Distinct();
like image 130
Grozz Avatar answered Nov 16 '22 20:11

Grozz


I'm bad with sql-like syntax so I'll write with extensions.

ctx.Leaves.Where(l => ctx.TreeInsects.Where( ti => list_with_insects.Select(lwi => lwi.InsectID).Contains( ti.InsectID ) ).Any( ti => ti.TreeID == l.TreeID ) );
like image 34
Dmitry Avatar answered Nov 16 '22 20:11

Dmitry