Materializing an ICollection structure containing subclasses

后端 未结 2 409
渐次进展
渐次进展 2021-01-28 23:37

I\'m reviewing some code that was written in the EF 4 days because it stands out during performance benchmarking.

The purpose of the code is to materialize an ICol

2条回答
  •  没有蜡笔的小新
    2021-01-29 00:09

    It cannot be said in advance if the performance will be better (sometimes executing a single complex query, especially with sub collection includes may have actually negative impact), but you can minimize the number of database queries to K, where K is the number of subclass types that need additional includes.

    You need to base the LoadSubclasses method on IQueryable representing all base entities, and execute one query per each subclass type using OfType filter:

    private void LoadSubclasses(IQueryable baseQuery)
    {
        // SubA
        baseQuery.OfType()
            .Include(x => x.Ref1.Options)
            .Load();
       // Similar for other subclasses
    }
    

    The usage with your sample would be:

    var parent = ctx.Parents.Include(p => p.Base).Where(...).Single();
    LoadSubclasses(ctx.Entry(parent).Collection(p => p.Base).Query());
    

    or more generally:

    var parentQuery = ctx.Parents.Where(...);
    var parents = parentQuery.Include(p => p.Base).ToList();
    LoadSubclasses(parentQuery.SelectMany(p => p.Base));
    

提交回复
热议问题