EF LINQ 查询性能优化

1、适时的使用AsNoTracking()进行数据查询,可提高执行效率,他是无跟踪查询,即查询的实体无法进行更改操作。Update无效

var customer = context.Customer.AsNoTracking().Where(p=>p.Name == 'zhangsan').FirstOrDefault();
customer.Age = 30;
context.SaveChanges();
//以上代码无法更新数据到数据库

  

2、EF 中使用AsNonUnicode(),不加AsNonUnicode SQL中会有 N,加了AsNonUnicode后,SQL中没有N ,使用 N 前缀(查询过程中需要把数据库默认格式转化为Unicode 格式来查询,因此:性能被拉低),当然如果查询包含中文字符等建议不要使用该方法

执行如下语句,并用SqlProfiler监控其SQL:

var list = context.Customer.Queryable().Where(w => w.CustomerId == guid && w.Name == "xxx")
.Select(s => new
{
Age = s.Age,
Name = s.Name
})
.ToList();

  

生成SQL如下:

SELECT 1 AS [C1],
[Extent1].[Age] AS [Age],
[Extent1].[Name] AS [Name]
FROM [dbo].[FL_Customer] AS [Extent1]
WHERE ([Extent1].[CustomerId] = 'f97317a1-21e1-4a6e-b1f9-960fc1def7eb' /* @p__linq__0 */)
AND (N'xxx' = [Extent1].[Name])

  

下面使用AsNonUnicode():

var list = context.Customer.Queryable().Where(w => w.CustomerId == guid && w.Name == EntityFunctions.AsNonUnicode("xxx"))
.Select(s => new
{
Age = s.Age,
Name = s.Name
})
.ToList();

  

生成SQL如下:

SELECT 1 AS [C1],
[Extent1].[Age] AS [Age],
[Extent1].[Name] AS [Name]
FROM [dbo].[FL_Customer] AS [Extent1]
WHERE ([Extent1].[CustomerId] = 'f97317a1-21e1-4a6e-b1f9-960fc1def7eb' /* @p__linq__0 */)
AND ('xxx' = [Extent1].[Name])

  

3、判断数据库是否存在某条数据时,请使用Any(),不要使用Count()

推荐:
var query = context.Customer.Any(p=>p.Name =='张三');
少用:
var result = context.Customer.Where(p=>p.Name == '张三').Count() > 0;

  

4、Where条件中,判断数组时,请使用Contains(),不要使用Any(),否则可能在查询时,出现如下错误信息:
  错误信息:Too high level of nesting for select

推荐:
var list = new List<int>{1,2,3,4,5,6,6,8,9,10};
var query = context.Customer.Where(p=>list.Contains(p.Id)).ToList();
慎用:
var list = new List<int>{1,2,3,4,5,6,6,8,9,10};
var query = context.Customer.Where(p=>list.Any(c=> c == p.Id)).ToList();

  

posted @ 2020-06-24 18:12  yuyoho  阅读(2033)  评论(0编辑  收藏  举报