While searching a solution to build Where clause in LINQ queries dynamically, I found a ScottGu’s post about Dynamic Expression API. You can look here.
To use Dynamic expressions you need to install package in NuGet package manager. The current version is 1.0.6.
1 |
Install-Package System.Linq.Dynamic |
Then add namespace to your code.
1 |
using System.Linq.Dynamic; |
Now you can write a LINQ query in dynamic expression form. You can even use it against Entity Framework. The following query is equivalent to the first example in my post Querying Entity Model. Part 14 – Dynamic Where Clause.
1 2 |
var query15 = ctx.Clients .Where("CountryCode = @0 and Phones.All(CountryCode = @1)", "US", "US"); |
In my case EF generates the following T-SQL query.
1 2 3 4 5 6 7 8 9 10 11 |
SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], [Extent1].[CountryCode] AS [CountryCode], [Extent1].[Timestamp] AS [Timestamp] FROM [dbo].[Clients] AS [Extent1] WHERE (N'US' = [Extent1].[CountryCode]) AND ( NOT EXISTS (SELECT 1 AS [C1] FROM [dbo].[Phones] AS [Extent2] WHERE ([Extent1].[Id] = [Extent2].[ClientId]) AND (( NOT ((N'US' = [Extent2].[CountryCode]) AND ([Extent2].[CountryCode] IS NOT NULL))) OR (CASE WHEN (N'US' = [Extent2].[CountryCode]) THEN cast(1 as bit) WHEN ( NOT ((N'US' = [Extent2].[CountryCode]) AND ([Extent2].[CountryCode] IS NOT NULL))) THEN cast(0 as bit) END IS NULL)) )) |