Entity framework. Need help filtering results

后端 未结 3 605
傲寒
傲寒 2021-01-21 15:46

Need to select data in entity framework but need to filter on the childrent and grandchildren

i have 4 tables. Parent -> Child -> GrandChild -> GreatGran

3条回答
  •  [愿得一人]
    2021-01-21 16:20

    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?

提交回复
热议问题