Entity framework. Need help filtering results

后端 未结 3 606
傲寒
傲寒 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:06

    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;
    
    0 讨论(0)
  • 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?

    0 讨论(0)
  • 2021-01-21 16:25

    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))));
    
    0 讨论(0)
提交回复
热议问题