I have this code:
string name ="M";
Expression<Func<Organization, bool>> getExpression1 = r => r.Name.Contains(name);
Expression<Func<Organization, bool>> getExpression2 = r => r.Name.Contains("M");
GetOrgListBy(getExpression);
GetOrgListBy(getExpression2);
public IEnumerable<Organization> GetOrgListBy(Expression<Func<Organization, bool>> filter)
{
return DataContext.Parties.OfType<Organization>().Where(filter).ToList();
}
Question:
I am passing a simple expression to a repository function
that gets List<Organization> by matching the name passed.
When I view the sql trace for getExpression1 (uses a string variable), the expression generates a [Name] like plinq_variable sql statement
which omits the % operator. My intention is to generate a
[Name] like '%' + plinq_variable + '%' sql statement
However, when I when using getExpression2 (hard-coded the string), the expression successfully
generates a [Name] like N'%M%' sql statement.
Why doesn’t getExpression1 generate the % operator?
How can I make it generate a % operator in the sql just like getExpression2?
The first expression translates into a parametrized SQL query. The variable in the Where clause …
… is set to the value
when the query is executed. The second expression translates to a SQL query with a hardcoded string literal:
Then this query is directly executed.
The result for both expressions and queries is the same.