在实体框架查询string.Trim()的行为 [英] Behaviour of string.Trim() in an Entity Framework query

查看:141
本文介绍了在实体框架查询string.Trim()的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图名称列表复制到SQL Server表,对此我有一个实体框架的项目设置。

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!

要我惊讶的是,上面没有工作,我期望的方式。我发现,同时分析了上述说法,认为如果(!context.Names.Any( N =方式> n.Value == nameToCopy.Trim())实际上并不查询nameToCopy的修剪版本 - 几个查询名字对他们的最后空格

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?

感谢

推荐答案

总的结果应该是一样的。 ?!你怎么分析

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

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

上面,LINQ到实体 .Trim()转化为TSQL RTRIM(LTRIM())和字符串变量被发送到SQL Server的原始状态并修整作为查询的一部分。

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)

尽管上述情况, .Trim()是一个正常的 System.String.Trim()和字符串变量被之前发送到SQL Server修整。

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

这篇关于在实体框架查询string.Trim()的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆