Search code examples
asp.netlinqc#-4.0entity-framework-6.1

LINQ query select entity and its collection query


I have an entity called Parent which has List of Children in it. now i want to select a parent and all its children order by display order.

    entities:- class parent{
                          Int id;
                          List<Child> children;
                           }

                class Child{ 
                            String name;
                            DateTime DOB;
                            Int DisplayOrder;
                           }

earlier i was getting a parent from Database using Linq to Entity as

                context.Parents.Find(id);

This was doing everything fine. but now my requirement has changed now i need to select its children order by their display order. how can i do that. Any help is appreciated.

update parent class:-

              class parent{
                        public  Int id;
                        public virtual List<Child> children;
                           }

Solution

  • From info you provided I guess that you using your children somewhere to display them so you can use just parent.children.OrderBy(x => x.DisplayOrder).ToList() instead of simply parent.children that I suppose you had before.

    Update 1.

    Also I as far as I remember Find won't include your children. So worth to try something like:

    var parent = context.Parents.Include(x => x.children).FirstOrDefault(x => x.id = id);
    parent.children = parent.children.OrderBy(x => x.DisplayOrder).ToList();