Comments (3)
If you are building predicate for EF you are doing this in wrong way. PredicateBuilder
will not help here.
Create question on StackOverflow with detailed description what you ate trying to achieve.
from linqkit.
@sdanyliv I am indeed doing that, I followed the demo you had in the Readme calling AsExpandable()
and using predicate.Compile()
everything seems to be working fine I don't see what's wrong with that? It's just this single problem that was stopping it from working on some cases because no error was thrown.
Here's the link to the demo app I made if you want to test it.
from linqkit.
@elf-is You are referring to DataTableService.SearchAColumn? I believe, that you misunderstand the behaviour of EF Core and your Database here, and there isn't a lot LINQKit can do about this. It may also be, that you would need to push for a C# Language specification change.
So first, what does EF Core do with Expression
s?
- EF Core tries to translate C#-function-calls into SQL
- It seems you are using Pomelo.EntityFrameworkCore.MySql as database provider, that documents that
stringValue.Contains(value)
is translated intoexpr LIKE pat [ESCAPE 'escape_char']
orLOCATE(substr,str)
. See https://github.com/PomeloFoundation/Pomelo.EntityFrameworkCore.MySql/wiki/Translations#string-functions - MySQL states for both, that if any argument is
NULL
, the result isNULL
. There is no exception/error here andNULL
for most aspects behaves like false in boolean-context
Second, if you intend to use the predicate outside EF Core you basically hit the limits of the C# compiler/C# Language specification. For all I know you can only use the expressions present in .NET 3.5 directly in source code and have it translated for you into an Expression
tree, see also https://learn.microsoft.com/en-us/dotnet/csharp/advanced-topics/expression-trees/#limitations . What you can do right now, is to write your own helper like
public class CoalescingTests
{
[Theory]
[InlineData(null, false)]
[InlineData("x", true)]
[InlineData("y", false)]
public void NullCoalesce(string value, bool expectation)
{
Expression<Func<string, bool>> expression = s => s.IfNotNull(str => str.Contains("x"), () => false);
Assert.Equal(expectation, expression.Invoke(value));
var expanded = expression.Expand();
Assert.DoesNotContain("IfNotNull", expanded.ToString());
Assert.Equal(expectation, expanded.Invoke(value));
}
}
public static class CoalescingExtensions
{
[Expandable(nameof(IfNotNullWithDefault))]
public static TResult IfNotNull<TIn, TResult>(this TIn value, Expression<Func<TIn, TResult>> then, Expression<Func<TResult>> @else)
{
return value != null ? then.Invoke(value) : @else.Invoke();
}
private static Expression<Func<TIn, Expression<Func<TIn, TResult>>, Expression<Func<TResult>>, TResult>> IfNotNullWithDefault<TIn, TResult>()
{
return (value, then, @else) => value != null ? then.Invoke(value) : @else.Invoke();
}
}
Calling Expand()
results in s => IIF((s != null), s.Contains("x"), False)
. This differs from ?.
in that it does not define a variable for the checked s
. If s
actually is a computed property, you may want to modify the expansion, to first assign the value to a local variable, as otherwise expanding will spread the property access to all places. Given that you build your predicate it may however be better memory-wise to create the temporary variable once and use it in all predicates.
This would be an expansion with local variable (not supported for .NET 3.5):
private static Expression<Func<TIn, Expression<Func<TIn, TResult>>, Expression<Func<TResult>>, TResult>> IfNotNullWithDefault<TIn, TResult>()
{
var valueParameter = Expression.Parameter(typeof(TIn), "value");
var value = Expression.Parameter(typeof(TIn), "v");
var then = Expression.Parameter(typeof(Expression<Func<TIn, TResult>>), "then");
var @else = Expression.Parameter(typeof(Expression<Func<TResult>>), "else");
return Expression.Lambda<Func<TIn, Expression<Func<TIn, TResult>>, Expression<Func<TResult>>, TResult>>(
Expression.Block(
new[] {value},
Expression.Assign(value, valueParameter),
Expression.Condition(
Expression.NotEqual(value, Expression.Constant(null, typeof(TIn))),
Expression.Invoke(then, value),
Expression.Invoke(@else))),
valueParameter, then, @else
);
}
Update: tried to provide shorter code-samples. Defining & assigning variables sadly isn't supported in expression-trees, so it takes up more lines
from linqkit.
Related Issues (20)
- ForEach extension method? HOT 2
- ExpressionVisitor.VisitConditional might fail if used in polymorphism HOT 1
- Timestamp in nuget dependencies HOT 2
- QueryOptimizer with EFCore? HOT 5
- Plugging Expressions into EntitySets / EntityCollections using compile doesnt work HOT 1
- Empty top-level Timestamp namespace appears in 1.2.2 causing CS0118 errors when a Timestamp type already exists in used namespace HOT 2
- Cannot use async operations with AsExpandable HOT 2
- PredicateBuilder cannot fill in parameter in SQLite when building expression. HOT 2
- No support for `Expression.Default` HOT 2
- EF Core 7 Json column projections - LINQ expression could not be translated HOT 2
- WithExpressionExpanding not expanding LINQ queries properly HOT 1
- how to do apply LINQ using ExpressionBuilder on NotMapped property HOT 1
- Why so many different versions targeting different versions of .NET? HOT 1
- AggregateBalanced overload for `Expression<Func<Type, bool>>[]`? HOT 1
- Error expanding a lambda which calls `Invoke()` on an inner expression which references outer parameter HOT 1
- JSON projection should support nested paths
- LinqKit.Core 1.2.5 is not compatible with net8.0 HOT 17
- linqkit.microsoft.entityframeworkcore is missing NuGet package README file
- How to use LinqKit in non static method?
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from linqkit.