0

I am creating a dictionary to use in my application like following. This is for entity framework.

var expressions = new Dictionary<string, Func<Expression, Expression, Expression>>
{
    { "is equal to", Expression.Equal },
    { "greater then", Expression.GreaterThan }
};

But I need a Like expression "Expression.Like" for sql like query. But this method does not exist.

Expression.Equal definition is like following:

public static BinaryExpression Equal(Expression left, Expression right)

So I need to create a custom method named Like . How can I do this? I could not found.

public static BinaryExpression Like(Expression left, Expression right)
{
   ???
}
barteloma
  • 6,403
  • 14
  • 79
  • 173

2 Answers2

0

You can get this from DbFunctions, Something like this

var methodInfo = typeof(DbFunctions).GetMethod(nameof(DbFunctions.Like), new Type[] { typeof(string) });

Also below is the definition for like function. It will be helpful

        //
        // Summary:
        //     When used as part of a LINQ to Entities query, this method invokes the canonical
        //     Like EDM operator to match an expression.
        //
        // Parameters:
        //   searchString:
        //     The string to search.
        //
        //   likeExpression:
        //     The expression to match against.
        //
        // Returns:
        //     True if the searched string matches the expression; otherwise false.
        //
        // Remarks:
        //     You cannot call this function directly. This function can only appear within
        //     a LINQ to Entities query. This function is translated to a corresponding function
        //     in the database.
        [SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames", MessageId = "string")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "searchString")]
        [SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "likeExpression")]
        public static bool Like(string searchString, string likeExpression);
Hammad Shabbir
  • 722
  • 1
  • 6
  • 13
0

Not sure if this is what you're looking for, but you could just create an extension method.

public static class MyExtensions
{
    public static BinaryExpression Like(this BinaryExpression obj, Expression left, Expression right)
    {
        //code here...
    }
}
KvartzC
  • 21
  • 5
  • I need SQL like or string Ccntains method implementaion. – barteloma Jun 24 '21 at 06:58
  • Not sure what you're trying to accomplish, could you provide a use case of your Dictionary? Maybe you just want to use .Contains()? Have a look at [this answer](https://stackoverflow.com/a/5374491/15980732). – KvartzC Jun 24 '21 at 07:09