Behaviour of string.Trim() in an Entity Framework query

c#, entity-framework, sql-server, string, trim

Solution

The overall result should be the same. How are you profiling?

!context.Names.Any(n => n.Value == nameToCopy.Trim())

Above, the Linq to Entities `.Trim()` is converted to TSQL `RTRIM(LTRIM())` and the string var is sent to SQL server in its original state and trimmed as part of the query.

string trimmedName = nameToCopy.Trim()
if (!context.Names.Any(n => n.Value == trimmedName)

Whereas above, the `.Trim()` is a normal `System.String.Trim()` and the string var is trimmed prior to sending to SQL Server.

Problem

I am trying to copy a list of names into a SQL Server table, for which I have an Entity Framework project setup for. The list of names has duplicate values, and several have spaces on the end of them. I wish to only insert names that aren't already in the table, as well as trim the spaces from the end of them. Seems fairly simple, right? My solution was this: ``` if (!context.Names.Any(n => n.Value == nameToCopy.Trim()) context.Names.Add(nameToCopy.Trim()) ``` NB. this isn't my exact code, just an example, so no need to mention that I'm trimming twice! To my surprise, the above doesn't work the way I expected. I found whilst profiling the above statement, that the `if (!context.Names.Any(n => n.Value == nameToCopy.Trim())` doesn't actually query for a trimmed version of nameToCopy - several of the queried names had spaces on the end of them. If, however, I do the below instead, it works as expected: ``` string trimmedName = nameToCopy.Trim() if (!context.Names.Any(n => n.Value == trimmedName) context.Names.Add(trimmedName) ``` Can anyone explain why the first solution doesn't use a trimmed version of the string in the database query? Thanks

Original source