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

放肆的年华 提交于 2020-01-01 16:58:55

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17414223/behaviour-of-string-trim-in-an-entity-framework-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!