问题
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