Home > Mobile >  NOT LIKE in EF core (expression tree)
NOT LIKE in EF core (expression tree)

Time:09-02

I'm building queries dynamically and i'm having an issue implementing NOT LIKE. My LIKE looks like so:

case "LIKE":
{
    var memberTypeConverter = TypeDescriptor.GetConverter(member.Type);
    var constant = Expression.Constant(value == null ? null : memberTypeConverter.ConvertFrom(value.ToString()!), member.Type);

    body = Expression.Call(
        typeof(DbFunctionsExtensions),
        nameof(DbFunctionsExtensions.Like),
        Type.EmptyTypes,
        Expression.Property(null, typeof(EF), nameof(EF.Functions)),
        member,
        constant
    );
    break;
}

This works, but there is no DbFunctionsExtensions.NotLike or something along those lines, and i'm not sure how to negate the Like.

I tried using something like IsFalse but that did not work.

body = Expression.IsFalse(Expression.Call(
                        typeof(DbFunctionsExtensions),
                        nameof(DbFunctionsExtensions.Like),
                        Type.EmptyTypes,
                        Expression.Property(null, typeof(EF), nameof(EF.Functions)),
                        member,
                        constant
                        )`
...

How can I get an expression that evaluates to a NOT LIKE query? How could I write NOT LIKE on a normal Queryable?

CodePudding user response:

You just need to wrap the expression in an Expression.Not to reverse the logic. So it could be this:

...

body = Expression.Call(
    typeof(DbFunctionsExtensions),
    nameof(DbFunctionsExtensions.Like),
    Type.EmptyTypes,
    Expression.Property(null, typeof(EF), nameof(EF.Functions)),
    member,
    constant
);

body = Expression.Not(body); // <--- Add this

CodePudding user response:

Like DavidG pointed out in the comments, the solution is simply Expression.Not

body = Expression.Not(Expression.Call(
        typeof(DbFunctionsExtensions),
        nameof(DbFunctionsExtensions.Like),
        Type.EmptyTypes,
        Expression.Property(null, typeof(EF), nameof(EF.Functions)),
        member,
        constant
    )
);

It gives the right query, although with some weird parenthesis.

WHERE NOT ([l].[ErrorMessage] LIKE N'Duplicate file: ')
  • Related