Reputation: 21
how can i do something like that?
public static class CustomExtensions
{
public static IQueryable<TEntity> CustomWhere<TEntity>(this
IQueryable<TEntity> entities,
Expression<Func<TEntity, bool>> getProperty,
bool isTrue)
{
return isTrue ? entities : entities.Where(getProperty);
}
}
var users = (
from user in _context.Users
let userChange = _context.UsersChange.CustomWhere(e => e.RegisterName == request.RegisterName,
string.IsNullOrEmpty(request.RegisterName)).FirstOrDefault()
select new
{
test = userChange
}).FirstOrDefault();
now i have error "The LINQ expression could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation EF Core 3.1"
Upvotes: 2
Views: 1319
Reputation: 205759
Custom extension methods can only be used with top level queryables, since that's the only case when they are actually executed. When used inside query expression tree (as in your example), the "call" is just recorded, but never called, and during the translation they are treated like any unknown method.
Hence the solution is to move the call (of course when possible) to a top level query variable, and then use the variable inside the actual query, e.g.
var userChanges = _context.UsersChange
.CustomWhere(e => e.RegisterName == request.RegisterName,
string.IsNullOrEmpty(request.RegisterName));
// Note that the above just defines a query without executing it
// Now it can be used inside the main query
var users = (
from user in _context.Users
let userChange = userChanges.FirstOrDefault()
select new
{
test = userChange
}
);
Upvotes: 2