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;
(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();
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 ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With