« LINQKit » : différence entre les versions
De Banane Atomic
Aller à la navigationAller à la recherche
Ligne 16 : | Ligne 16 : | ||
context.Groups.AsExpandable().Where(x => x.Users.Any(expression.Compile())); | context.Groups.AsExpandable().Where(x => x.Users.Any(expression.Compile())); | ||
// Compile never actually runs; AsExpandable will strip out the call to Compile and substitute it with a correct expression tree | // Compile never actually runs; AsExpandable will strip out the call to Compile and substitute it with a correct expression tree | ||
</kode> | |||
= [https://github.com/scottksmith95/LINQKit#combining-expressions Combining Expressions] = | |||
<kode lang='csharp'> | |||
Expression<Func<User, bool>> e1 = x => x.Name.StartsWith("U"); | |||
Expression<Func<User, bool>> e2 = x => x.Name.EndsWith("2"); | |||
Expression<Func<User, bool>> e3 = x => e1.Invoke(x) && e2.Invoke(x); | |||
Console.WriteLine(e3.Expand()); // x => (x.Name.StartsWith("U") AndAlso x.Name.EndsWith("2")) | |||
</kode> | </kode> | ||
Version du 14 mars 2021 à 12:20
Links
- LINQKit on GitHub
AsExpandable
Expression<Func<User, bool>> expression = x => x.Name.EndsWith("2"); context.Users.Where(expression); // works fine ! // as x.Users is not a IQueryable, Any cannot take an Expression but a Func // so we need to use Compile to get Func from Expression context.Groups.Where(x => x.Users.Where(expression.Compile())); // Entity Framework will throw an exception // solution: use AsExpandable context.Groups.AsExpandable().Where(x => x.Users.Any(expression.Compile())); // Compile never actually runs; AsExpandable will strip out the call to Compile and substitute it with a correct expression tree |
Combining Expressions
Expression<Func<User, bool>> e1 = x => x.Name.StartsWith("U"); Expression<Func<User, bool>> e2 = x => x.Name.EndsWith("2"); Expression<Func<User, bool>> e3 = x => e1.Invoke(x) && e2.Invoke(x); Console.WriteLine(e3.Expand()); // x => (x.Name.StartsWith("U") AndAlso x.Name.EndsWith("2")) |
Installation
dotnet add package LinqKit.Microsoft.EntityFrameworkCore |