I am trying to make my code a little bit cleaner and easier to read but I am getting an efcore exception (they indicate this might be a limitation), just wanted to see if anyone can help.
I am using .net3.1 and efcore also 3.1.
Original code working:
public Response GetAll(long myId, DataSourceLoadOptions loadOptions)
{
var dbContext = ContextFactory.GetContext<IMyContext>();
var query = dbContext.Table1.Where(_ => _.Id == myId).Select(ent1 => new
{
Id = ent1.Id,
State = ent1.State,
MatCode = ent1.Mat.Code,
AmountToFulfill = ent1.AmountRequested,
AmountReserved = dbContext.Table2.Where(matres => matres.Ent1Id == ent1.Id && matres.State == MaterialReservationState.Active).Select(_ => _.AmountReserved).Sum(),
LastChangeTime = ent1.ChangeTime,
});
return query.ToList();
}
Not working code:
public Response GetAll2(long myId, DataSourceLoadOptions loadOptions)
{
var dbContext = ContextFactory.GetContext<IMyContext>();
var query = dbContext.Table1.Where(_ => _.Id == myId).Select(ent1 => new
{
Id = ent1.Id,
State = ent1.State,
MatCode = ent1.Mat.Code,
AmountToFulfill = ent1.AmountRequested,
AmountReserved = GetReservedAmount(dbContext, ent1).Sum(),
LastChangeTime = ent1.ChangeTime,
});
return query.ToList();
}
private static IQueryable<int> GetReservedAmount(IMyContext dbContext, IEntity1 ent1)
{
return dbContext.Table2
.Where(matres => matres.Ent1Id == ent1.Id && matres.State == MaterialReservationState.Active)
.Select(_ => _.AmountReserved);
}
Exception:
[21:26:28.1605 ERR] An unhandled exception has occurred while executing the request. {EventId={Id=1, Name="UnhandledException"}, SourceContext="Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware", RequestId="0HxxxxxA83M7JB:00000001", RequestPath="/xxxxxxxxxx/2", SpanId="|5exxx39-48248xxxxx5b806.1.eee74277_", TraceId="5e3cde39-4824xxxxx", ParentId="|5e3cxxde39-48248xxxxxa25b806.1.", ConnectionId="0xxxxxx", ThreadId=11} System.InvalidOperationException: Processing of the LINQ expression 'ClassName.GetAll2( dbContext: __dbContext_1, op: (NavigationTreeExpression Value: (EntityReference: Entity1) Expression: o.Outer)) .Sum()' by 'NavigationExpandingExpressionVisitor' failed. This may indicate either a bug or a limitation in EF Core. See https://go.microsoft.com/fwlink/?linkid=2101433 for more detailed information. at Microsoft.EntityFrameworkCore.Query.Internal.NavigationExpandingExpressionVisitor.VisitMethodCall(MethodCallExpression methodCallExpression) .......