I have upgraded my web app to NET Core 3 and some EF LINQ queries that were returning values correctly in NET Core 2 now are erroring. I have the following code in my OrderManager class:
private TResult GetOrder<TResult>(Func<Order, bool> condition, Func<Order, TResult> selector)
{
return _context.Orders
.Where(x => condition(x))
.Include(x => x.OrderStocks)
.ThenInclude(x => x.Stock)
.ThenInclude(x => x.Product)
.Select(selector).FirstOrDefault();
}
public TResult GetOrderById<TResult>(int id, Func<Order, TResult> selector)
{
return GetOrder(order => order.Id == id, selector);
}
public TResult GetOrderByReference<TResult>(string reference, Func<Order, TResult> selector)
{
return GetOrder(x => x.OrderRef == reference, selector);
}
Looks like dotnet 3 doesn't like that.Where statement:
System.InvalidOperationException: 'The LINQ expression 'DbSet.Where(o => Invoke(__condition_0, o[Order]) )' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to either AsEnumerable(), AsAsyncEnumerable(), ToList(), or ToListAsync(). See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.'
Does anyone know how this query could be re-written correctly? I have tried to add AsEnumerable() in line: return _context.Orders but thats not the fix, I am a bit blocked here as I am not an expert in LINQ.
GetOrder
needs to take Expression<Func<Order, bool>>
as condition
parameter not Func<Order, bool>
:
private TResult GetOrder<TResult>(Expression<Func<Order, bool>> condition, Func<Order, TResult> selector)
After changing the parameter you will need to change Where
clause also:
_context.Orders
.Where(condition)
It seems previously your query was executed on client side, see the breaking changes list .
Though it should be fine to have Func
for selector
cause it is last statement in the query, but bear in mind that it will fetch all columns into memory and then preform mapping using needed ones.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.