How to write Repository method for .ThenInclude in EF Core 2

前端 未结 3 1826
攒了一身酷
攒了一身酷 2020-12-08 03:22

I\'m trying to write a repository method for Entity Framework Core 2.0 that can handle returning child collections of properties using .ThenInclude, but I\'m having trouble

3条回答
  •  暖寄归人
    2020-12-08 04:06

    I found this repository method online and it does exactly what I wanted. Yared's answer was good, but not all the way there.

    /// 
    /// Gets the first or default entity based on a predicate, orderby delegate and include delegate. This method default no-tracking query.
    /// 
    /// The selector for projection.
    /// A function to test each element for a condition.
    /// A function to order elements.
    /// A function to include navigation properties
    /// True to disable changing tracking; otherwise, false. Default to true.
    /// An  that contains elements that satisfy the condition specified by .
    /// This method default no-tracking query.
    public TResult GetFirstOrDefault(Expression> selector,
                                              Expression> predicate = null,
                                              Func, IOrderedQueryable> orderBy = null,
                                              Func, IIncludableQueryable> include = null,
                                              bool disableTracking = true)
    {
        IQueryable query = _dbSet;
        if (disableTracking)
        {
            query = query.AsNoTracking();
        }
    
        if (include != null)
        {
            query = include(query);
        }
    
        if (predicate != null)
        {
            query = query.Where(predicate);
        }
    
        if (orderBy != null)
        {
            return orderBy(query).Select(selector).FirstOrDefault();
        }
        else
        {
            return query.Select(selector).FirstOrDefault();
        }
    }
    

    Usage:

    var affiliate = await affiliateRepository.GetFirstOrDefaultAsync(
        predicate: b => b.Id == id,
        include: source => source
            .Include(a => a.Branches)
            .ThenInclude(a => a.Emails)
            .Include(a => a.Branches)
            .ThenInclude(a => a.Phones));
    

提交回复
热议问题