Need to select data in entity framework but need to filter on the childrent and grandchildren
i have 4 tables. Parent -> Child -> GrandChild -> GreatGran
Using linq you should need something like this.
var q = from q1 in dbContext.Parent
join q2 in dbContext.Children
on q1.key equals q2.fkey
join q3 in ........
where q4.col1 == 3000
select q1;
Your table structure - if your example is not just for illustration, leads me to think you may want to think more about your model here (i.e. are children separate entity types or should they be a defined relationship?)
What you describe is a simple joins and where clause though, and is written essentially the same way: assuming you are returning DBSet from your DBContext:
_context.Parents.Join(context.Child, p=>p.Parent.ID, c=>c.ParentID)
.Join(...Grandchild...).Where(o=>o.Column5=600)
.Join(...GreatGrandChild...).Where(o=>o.Column3=1000)
EDIT to get back the strongly typed entities you might need to do something like:
var greatgrandchildren = context.GreatGrandchildren.Where(o=>o.Column3=1000).ToList();
var grandchildren = context.Grandchildren.Where(o=>o.Column3=600 and greatgrandchildren.contains(o)).ToList();
var children = context.Children.Where(o=>grandchildren.Contains(o)).ToList();
var parents = context.Parent(o=>children.Contains(o).ToList();
My syntax might be off, and someone can add, can I avoid .ToList() to prevent roundtrips until the last call?
This query should do what you want. Yes, it is a bit of a mess because it is so deeply nested.
var result = context.Parent
.Where(parent => parent.Child
.Any(child => (child.Column5 == 600) &&
child.GrandChild
.Any(grandchild => grandchild.GreatGrandChild
.Any(greatgrandchild => greatgrandchild.Column3 == 1000))));