EF Core 2.1 Props inside where cause null reference

删除回忆录丶 提交于 2019-12-11 07:33:16

问题


When I migrated from EF 1.1 to 2.1 I started getting null reference error when iterating inside where condition, it seems like StatusCashAdvanceList is not loaded at the time where is executed.

CashAdvance.cs:

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

Stack Trace:

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

Null reference:

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

This is the props method used inside Where

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

This works, but I think it's just a workaround:

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

来源:https://stackoverflow.com/questions/50994289/ef-core-2-1-props-inside-where-cause-null-reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!