按lambda订购时,EF Core导航属性会消失

时间:2018-11-16 18:32:12

标签: c# entity-framework-core

我有Item实体,它与ItemVariant有一对多的关系。我尝试按ItemVariant的价格订购商品,但ItemVariants导航属性(与任何其他导航属性一样)为空。有趣的是,在输入lambda之前它不是空的。仅当我在订购函数之前执行ToListAsync时,它才起作用。

// entities I use
public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }

    public ICollection<ItemVariant> ItemVariants { get; set; } = new List<ItemVariant>();
}

public class ItemVariant
{
    public int Id { get; set; }
    public int ItemId { get; set; }

    public Item Item { get; set; }
}

/// <summary>
/// Contains full information for executing a request on database
/// </summary>
/// <typeparam name="T"></typeparam>
public class Specification<T> where T : class
{
    public Expression<Func<T, bool>> Criteria { get; }
    public List<Expression<Func<T, object>>> Includes { get; } = new List<Expression<Func<T, object>>>();
    public List<Func<T, IComparable>> OrderByValues { get; set; } = new List<Func<T, IComparable>>();
    public bool OrderByDesc { get; set; } = false;

    public int Take { get; protected set; }
    public int Skip { get; protected set; }
    public int Page => Skip / Take + 1;
    public virtual string Description { get; set; }
}

// retrieves entities according to specification passed
public static async Task<IEnumerable<TEntity>> EnumerateAsync<TEntity, TService>(this DbContext context, IAppLogger<TService> logger, Specification<TEntity> listSpec) where TEntity: class
{
    if (listSpec == null)
        throw new ArgumentNullException(nameof(listSpec));
    try
    {
        var entities = context.GetQueryBySpecWithIncludes(listSpec);
        var ordered = ApplyOrdering(entities, listSpec);
        var paged = await ApplySkipAndTake(ordered, listSpec).ToListAsync();
        return paged;
    }
    catch (Exception readException)
    {
        throw readException.LogAndGetDbException(logger, $"Function: {nameof(EnumerateAsync)}, {nameof(listSpec)}: {listSpec}");
    }
}

// applies Includes and Where to IQueryable. note that Include happens before OrderBy.
public static IQueryable<T> GetQueryBySpecWithIncludes<T>(this DbContext context, Specification<T> spec) where T: class
{
    // fetch a Queryable that includes all expression-based includes
    var queryableResultWithIncludes = spec.Includes
        .Aggregate(context.Set<T>().AsQueryable(),
            (current, include) => current.Include(include));
    var result = queryableResultWithIncludes;
    var filteredResult = result.Where(spec.Criteria);
    return filteredResult;
}

// paging
public static IQueryable<T> ApplySkipAndTake<T>(IQueryable<T> entities, Specification<T> spec) where T : class
{
    var result = entities;
    result = result.Skip(spec.Skip);
    return spec.Take > 0 ? result.Take(spec.Take) : result;
}

// orders IQueryable according to Lambdas in OrderByValues
public static IQueryable<T> ApplyOrdering<T>(IQueryable<T> entities, Specification<T> spec) where T : class
{
    // according to debugger all nav properties are loded at this point
    var result = entities;
    if (spec.OrderByValues.Count > 0)
    {
        var firstField = spec.OrderByValues.First();
        // but disappear when go into ordering lamda
        var orderedResult = spec.OrderByDesc ? result.OrderByDescending(i => firstField(i)) : result.OrderBy(i => firstField(i));
        foreach (var field in spec.OrderByValues.Skip(1))
            orderedResult = spec.OrderByDesc ? orderedResult.ThenByDescending(i => field(i)) : orderedResult.ThenBy(i => field(i));
        result = orderedResult;
    }
    return result;
}

这是我的控制器代码应用顺序的一部分。在EnumerateAsync之前被调用

protected override void ApplyOrdering(Specification<Item> spec)
{
    spec.AddInclude(i => i.ItemVariants);
    spec.OrderByValues.Add(i =>
    {
        // empty if ToListAsync() not called before
        if (i.ItemVariants.Any())
            return (from v in i.ItemVariants select v.Price).Min();
        return 0;
    });
}

在分页之前调用ToListAsync并不是最佳选择,因为由于尚未应用分页,这意味着加载的实体比需要的多得多(分页的结果也取决于排序)。也许有一些配置可以在需要时加载导航属性?

更新:尝试使用.UseLazyLoadingProxies(),但是在ItemVariants.Any(),我遇到了一个异常,并且我没有使用AsNoTracking()

  

为警告“ Microsoft.EntityFrameworkCore.Infrastructure.DetachedLazyLoadingWarning”而生成的错误:尝试对类型为“ ItemProxy”的分离实体延迟加载导航属性“ ItemVariants”。分离的实体或使用'AsNoTracking()'加载的实体不支持延迟加载。通过将事件ID'CoreEventId.DetachedLazyLoadingWarning'传递到'DbContext.OnConfiguring'或'AddDbContext'中的'ConfigureWarnings'方法,可以抑制或记录该异常。

1 个答案:

答案 0 :(得分:2)

此问题的根本原因是使用 delegate Func<T, IComparable>)而不是Expression<Func<...>>进行订购。

EF6只会在运行时抛出NotSupportedException,但是EF Core将切换到client evaluation

除了引入的效率低下外,客户评估目前还不能很好地与导航属性配合使用-似乎是在 急于加载/导航属性修复之前应用的,这就是为什么导航属性为{{1 }}。

即使在将来的某些发行版中将EF Core实现固定为“有效”,通常也应尽可能避免进行客户评估。这意味着您必须对所使用的规范模式实现的排序部分进行调整以使其与表达式一起使用,以便能够生成类似这样的内容

null

应该可以转换为SQL,因此可以评估服务器端,并且导航属性没有问题。