Tuesday, July 22, 2008

Like versus Contains

So have to figure this one out. Say you have:
private static Expression<Func<User, Boolean>> WhereLikeFirstNameLastNameUserName(String name)
{
  return currentUser => SqlMethods.Like(currentUser.UserName, "%" + name + "%")
  || SqlMethods.Like(currentUser.FirstName, "%" + name + "%")
  || SqlMethods.Like(currentUser.LastName, "%" + name + "%");
}
And
private static Expression <Func<User, Boolean>> WhereLikeFirstNameLastNameUserNameWithoutLike(String name)
{
  return currentUser => currentUser.UserName.Contains(name)
  || currentUser.FirstName.Contains(name)
  || currentUser.LastName.Contains(name);
}
The first one should look familiar, its part of the "dynamic" linq stuff I've been posting. Now guess which one gives me this SQL when profiled:
exec sp_executesql N
'SELECT
 [t0].[UserID],
 [t0].[FirstName],
 [t0].[LastName],
 [t0].[Password],
 [t0].[UserName],
 [t0].[UserTypeID]
FROM
 [dbo].[User] AS [t0]
WHERE
 ([t0].[UserName] LIKE @p0)
OR
 ([t0].[FirstName] LIKE @p1)
OR
 ([t0].[LastName] LIKE @p2)
ORDER BY
 [t0].[UserName]',

N'@p0 varchar(3),
 @p1 nvarchar(3),
 @p2 nvarchar(3)',
 @p0='%s%',
 @p1=N'%s%',
 @p2=N'%s%'
If you answered both, you are correct or you looked ahead for the answer and therefore are a tool. Now which do you think that...
query.ToList()
Produces the correct list? If you answered Contains, then you are correct again. If you are a tool, you probably looked ahead again... Why is this? I HAVE NO IDEA... Something I have to look into for sure.

No comments: