首页 > 解决方案 > EF Core 2.1 Props inside where 导致空引用

问题描述

当我从 EF 1.1 迁移到 2.1 时,在 where 条件内迭代时开始出现空引用错误,似乎在执行 where 时未加载 StatusCashAdvanceList。

CashAdvance.cs:

public virtual ICollection<StatusCashAdvance> StatusCashAdvanceList { get; set; }

堆栈跟踪:

NullReferenceException: Object reference not set to an instance of an object.
lambda_method(Closure , CashAdvance)
System.Linq.Enumerable+WhereSelectEnumerableIterator<TSource, TResult>.MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider._TrackEntities<TOut, TIn>(IEnumerable<TOut> results, QueryContext queryContext, IList<EntityTrackingInfo> entityTrackingInfos, IList<Func<TIn, object>> entityAccessors)+MoveNext()
Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider+ExceptionInterceptor<T>+EnumeratorExceptionInterceptor.MoveNext()
System.Collections.Generic.List<T>.AddEnumerable(IEnumerable<T> enumerable)
System.Linq.Enumerable.ToList<TSource>(IEnumerable<TSource> source)
[------].CashAdvanceController.Index() in CashAdvanceController.cs
+
            var cashAdvances= _context.CashAdvance

空引用:

var cashAdvances = _context.CashAdvance
                .Include(a => a.StatusCashAdvanceList)
                    .ThenInclude(s => s.ObjTypeStatusCashAdvance)
                .Where(a => a.ActualStatusCashAdvance.IdTypeStatusCashAdvance < PAYED)                
                .ToList();

这是 Where 里面使用的 props 方法

 public StatusCashAdvance ActualStatusCashAdvance{
   get {
       if(this.StatusAdiantamentoList.Count == 0)
           return null;               
       var status =  this.StatusCashAdvanceList
                         .OrderByDescending(a=> a.Data).First();
           return status;
       }               
}

这可行,但我认为这只是一种解决方法:

    var cashAdvances = _context.CashAdvance
        .Include(a => a.StatusCashAdvanceList)
            .ThenInclude(s => s.ObjTypeStatusCashAdvance)
        .Tolist()
        .Where(a => a.ActualStatusCashAdvance.IdTypeStatusCashAdvance < 
        PAYED)                
        .ToList();

标签: .net-coreentity-framework-coreef-core-2.0ef-core-2.1

解决方案


推荐阅读