How to order child collections of entities in EF

后端 未结 3 1168
旧时难觅i
旧时难觅i 2020-12-05 13:17

I have the following query:

public IEnumerable GetAllTeamsWithMembers(int ownerUserId)
        {
            return _ctx.Teams
                 .         


        
3条回答
  •  旧巷少年郎
    2020-12-05 13:51

    Unfortunately eager loading (Include) doesn't support any filtering or sorting of loaded child collections.

    But as stated in the accepted answer, you can sort each collection after they've been eager loaded. I wrote an extension method that handles sorting a collection by a child property easily in place so there is no need for reassignment:

    public static class Extensions
    {
        public static void SortOn(this List enumerable, Expression> expression)
        {
            var type = expression.Parameters[0].Type;
            var memberName = ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
    
            enumerable.Sort((x, y) =>
            {
                var first = (IComparable)type.GetProperty(memberName).GetValue(x);
                var second = (IComparable)type.GetProperty(memberName).GetValue(y);
                return first.CompareTo(second);
            });
        }
    }
    

    Then sorting the child collections could be succinctly written as:

    foreach (var team in teams)
        team.TeamMembers.SortOn(_ => _.Name);
    

提交回复
热议问题