4

我们的公司表是使用带有填充空间的字段创建的。

我无权更改数据库。

但是,我注意到当我使用 Trim() 函数创建 LINQ 查询时,性能会下降很多。

像这样简单的查询表明性能下降:

Companies
.Where(c => c.CompanyName.Equals("Apple"))
.Select(c => new {
  Tick = c.Ticker.Trim(),
  Address = c.Address.Trim()
});

有没有办法改变查询,以免性能损失?

还是这完全取决于我的 DBA?

4

3 回答 3

4

快速解决方案是在将您的公司名称提供给查询之前填充您的公司名称。例如,如果列是char(50)

var paddedName = "Apple".PadRight(50);
var result = Companies
 .Where(c => c.CompanyName.Equals(paddedName))
 .Select(c => new {
     Tick = c.Ticker.Trim(),
     Address = c.Address.Trim()
 });

但是,您应该考虑更正数据库以避免进一步的问题。

于 2013-08-05T04:07:34.817 回答
0

Other than Entity Framework, linq-to-sql can sometimes switch to linq-to-objects under the hood when it encounters method calls that can't be translated to SQL. So if you do

....
.Select(c => new {
  Tick = c.Ticker.TrimEnd().TrimStart(),
  Address = c.Address.TrimEnd().TrimStart()

you will notice that the generated SQL no longer contains LTRIM(RTRIM()), but only the field name and that the trims are executed in client memory. Apparently, somehow the LTRIM(RTRIM()) causes a less efficient query plan (surprisingly).

Maybe only TrimEnd() suffices if there are no leading spaces.

Further, I fully agree with p.s.w.g. that you should go out of your way to try and clean up the database in stead of fixing bad data in queries. If you can't do this job, find the right persons and twist their arms.

于 2013-08-06T14:27:19.170 回答
0

如果我们使用“Like”语句进行第一轮过滤并使其成为.ToList(),我还没有尝试过性能,第二轮仅在内部进行相等检查而不调用数据库。

var result = (Companies
            .Where(c => c.CompanyName.StartsWith("Apple"))
            .Select(c => new
            {
                Tick = c.Ticker.Trim(),
                Address = c.Address.Trim()
            })).ToList();

 var result1=result
            .Where(c=>c.CompanyName.Trim().Equals("Apple")) 
            .Select(c => c);
于 2013-08-05T05:56:54.040 回答