Updated on Kisan Patel
Problem:
Linq to Select Parent Objects Where Child Objects Have a Matching Child Object
linq how to select a parent with a child collection that contains one or many of an array (or list) of values
Querying Child Collections in LINQ
Solution:
Here’s example classes.
class Parent { int Id { get; set; } string Name { get; set; } List<Child> Childs { get; set; } } class Child { int ParentId { get; set; } [ForeignKey("ParentId")] Parent Parent { get; set; } string Address { get; set; } }
In the example above, If you would like to return all of the parents that contain a child with a specific ParentId.
context.Parents.Where(p => p.Childs.Any(y=> y.ParentId == yourId));