Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug when using StartsWith() #34

Open
mguinness opened this issue Nov 22, 2016 · 3 comments
Open

Bug when using StartsWith() #34

mguinness opened this issue Nov 22, 2016 · 3 comments

Comments

@mguinness
Copy link

There appears to be a bug when using StartsWith() method in a LINQ query:

var customers = _ctx.Customers.Where(c => c.CustomerName.StartsWith("a")).ToList();

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONCAT('a', '%') '%')'

SELECT * FROM `Customers` AS `c` WHERE `c`.`CustomerName` LIKE ('%' CONCAT('a', '%') '%')

Should probably be output as

SELECT * FROM `Customers` AS `c` WHERE `c`.`CustomerName` LIKE CONCAT('a', '%')

@eByte23
Copy link

eByte23 commented Nov 22, 2016

I can see why this is doing this straight away, it is doing a VisitLikeExpression and then VisitBinaryExpression. Should be an easy fix I'll have a look when I'm back at a computer.

@eByte23
Copy link

eByte23 commented Nov 22, 2016

After a quick look, it looks like something like this would fix this issue but its abit messy.
This would be in MySQLQuerySqlGenerator.cs

protected override Expression VisitBinary(BinaryExpression expression)
		{
			if(expression.NodeType == ExpressionType.Add && expression.Type == typeof(string))
			{
                if (expression.Right.ToString().Contains("%"))
                {
                    Visit(expression.Left);
                    return expression;
                }
                else if (expression.Left.ToString().Contains("%"))
                {
                    Visit(expression.Right);
                    return expression;
                }

				Sql.Append("CONCAT(");
				Visit(expression.Left);
				Sql.Append(", ");
				Visit(expression.Right);
				Sql.Append(")");

				return expression;
			}

			return base.VisitBinary(expression);
		}

@vvdimov
Copy link

vvdimov commented Dec 31, 2016

Suggested fix generates:
WHERE x.ColumnName LIKE ('%' @__parameter_0 '%')
which is not inline with StartWith.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants