I have Product entity and write a method in a repository class (using npgsql). But I get error :
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. System.InvalidOperationException: The LINQ expression 's => s.ProductId == EntityShaperExpression:
public class Product:IEntity
{
public string Id { get; set; }
public string SerialNo { get; set; }
public string Imei { get; set; }
public string Name { get; set; }
}
public class ProductInput
{
public string ProductId { get; set; }
public string SerialNo { get; set; }
public string Imei { get; set; }
}
public async Task<List<Product>> GetProducts(List<ProductInput> input) //EfCoreProductRepository.cs
{
var result = (from product in (await GetDbContextAsync()).Products
where input.Any(s => s.ProductId == product.Id && s.SerialNo == product.SerialNo && s.Imei == product.Imei)
select product).ToList();
return result;
}
How should I edit my query to avoid getting this error?
It looks like you're trying to retreieve DB rows that match your
inputrows by multiple criteria. There are multiple ways to do this, such as:inputdata into a table-valued (SQL Server) or typed-array (Postgres) parameter, or even a JSON string blob (horrible) and doing anINNER JOINwith that parameter.WHEREpart.inputin C# and executing individual queriesIn this author's opinion, Option 2 (Dynamically-built Linq Query) is the "best" overall here, so do it like so:
First, get
PredicateBuilder- it's a tiiiiiny dependency that makes it significantly easier to build-upOrpredicates with Linq. It's literally aclassyou copy-and-paste from Albahari's website.Second, use it like so:
PredicateBuilder
For posterity, I've reproduced
class PredicateBuilderhere: