优化实体框架查找方法

时间:2015-01-28 09:25:53

标签: entity-framework

以下是我如何获得Id的操作!

 Operation operation = db.Operations.Find(id):;

我想优化这行代码!因为我不想在id没有价值时发送请求。所以我写了以下这一行。

    Operation operation = id.HasValue? db.Operations.Find(id):null;

但我想知道我是否重新发明轮子!当参数为null时,E.F Find方法是否查询数据库?

1 个答案:

答案 0 :(得分:0)

使用SQL Server探查器进行测试非常容易。针对通用的IdentityContext:

int? id = 0;
var user = db.Users.Find(id);

Sql profiler结果:

exec sp_executesql N'SELECT TOP (2) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Email] AS [Email], 
    [Extent1].[EmailConfirmed] AS [EmailConfirmed], 
    [Extent1].[PasswordHash] AS [PasswordHash], 
    [Extent1].[SecurityStamp] AS [SecurityStamp], 
    [Extent1].[PhoneNumber] AS [PhoneNumber], 
    [Extent1].[PhoneNumberConfirmed] AS [PhoneNumberConfirmed], 
    [Extent1].[TwoFactorEnabled] AS [TwoFactorEnabled], 
    [Extent1].[LockoutEndDateUtc] AS [LockoutEndDateUtc], 
    [Extent1].[LockoutEnabled] AS [LockoutEnabled], 
    [Extent1].[AccessFailedCount] AS [AccessFailedCount], 
    [Extent1].[UserName] AS [UserName]
    FROM [dbo].[AspNetUsers] AS [Extent1]
    WHERE [Extent1].[Id] = @p0',N'@p0 int',@p0=0

再次使用空值

int? id = null
var user = db.Users.Find(id);

SQL探查器不会记录查询。

所以看起来你的.HasValue检查是不必要的。