I'm trying to retrieve from database the list of products which names contains, starts with or ends with any of list elements that I pass as parameter to the method executing the query.
I've tried both Linq approaches (method and query syntax)
Here is the relevant code of Linq method query, names being List of names passed as argument to the method:
var query = _dbContext.Products
.Where(p => p.IdExternalProduct == null &&
names.Any(name => p.ProductName.Contains(name)))
.Select(item => new ProductEntity() { Uuid = item.Uuid, Code = item.Code});
or
var query = _dbContext.Products
.Where(p => p.IdExternalProduct == null &&
names.Any(name => p.ProductName.StartsWith(name)))
.Select(item => new ProductEntity() { Uuid = item.Uuid, Code = item.Code});
And here is the query syntax approach:
IQueryable<ProductEntity> query = (
from p in _dbContext.Products
where
p.IdExternalProduct == null &&
(names != null && names.Count > 0 ? names.Any(name => p.ProductName.Contains(name)) : true)
select new ProductEntity()
{
Uuid = p.Uuid,
Code = p.Code
}
The exact same query works when I try with Equals
instead of Contains
, StartsWith
or EndsWith
.
I searched a lot and found a lot of resources but no solution worked for me.
Here are two related Stack overflow's questions where Jon Skeet recommends the same implementation.
Check if a string within a list contains a specific string with Linq
I'm using the version 6.0.10 of Entity Framework and SQL Server provider.
But it's seems that these formulas cannot be translated, throwing an exception with the following message:
The LINQ expression 'name => EntityShaperExpression:
Service.Product.Products
ValueBufferExpression:
ProjectionBindingExpression: EmptyProjectionMember
IsNullable: False
.ProductName.Contains(name)' 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 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.