CodexBloom - Programming Q&A Platform

implementing Dynamic LINQ Filtering on IQueryable in C# 10 - InvalidOperationException on Null Values

👀 Views: 56 💬 Answers: 1 📅 Created: 2025-06-08
c# linq ef-core dynamic-linq C#

I'm experimenting with I'm stuck on something that should probably be simple. I'm working with an scenario when trying to apply dynamic filtering on an `IQueryable<T>` collection using the `Dynamic LINQ` library in C# 10. The filtering criteria depend on user input, and I've implemented it like this: ```csharp var query = dbContext.Products.AsQueryable(); if (!string.IsNullOrEmpty(filterCriteria)) { query = query.Where(filterCriteria); } ``` However, whenever `filterCriteria` contains a condition that references a nullable property, such as `Price`, and the database has null values for this property, I encounter an `InvalidOperationException` with the message: "The LINQ expression could not be translated." For example, if `filterCriteria` is set to `Price > 50`, it works fine, but if it's `Price == null`, the exception is thrown. I’ve also tried using `.ToList()` before applying the `Where` clause to force execution, but that doesn't seem to resolve the scenario. I suspect it might be due to how the library translates the LINQ expression when it encounters null values. I checked the versions I’m using: `Dynamic LINQ 1.0.1` and EF Core `5.0.11`. Is there a way to handle nullable properties in dynamic filtering without running into these exceptions? Any insights or workarounds would be appreciated! My development environment is Linux. Any suggestions would be helpful.