Entity Framework使用Where方法查询单行记录,但生成的SQL语句没有Where子句是为什么?

在使用ENtityFramework查询数据的时候,其中有一个表,即使在Where方法中传入了查询条件,生成的SQL语句中始终不带Where子句,请问这是为什么?

调用栈:

public IList<Device> GetDeviceByNodeId(string nodeId)
            => GetModels(device => device.DeviceNodeId == nodeId).ToList();

public virtual IEnumerable<T> GetModels(Func<T, bool> exp)
            => EntitySet.Where(exp);

生成的SQL语句:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[DeviceTypeId] AS [DeviceTypeId], 
    [Extent1].[OriginalDeviceId] AS [OriginalDeviceId], 
    [Extent1].[DeviceCode] AS [DeviceCode], 
    [Extent1].[StatCode] AS [StatCode], 
    [Extent1].[DevicePassword] AS [DevicePassword], 
    [Extent1].[DeviceModuleGuid] AS [DeviceModuleGuid], 
    [Extent1].[DeviceNodeId] AS [DeviceNodeId], 
    [Extent1].[FirmwareSetId] AS [FirmwareSetId], 
    [Extent1].[ProjectId] AS [ProjectId], 
    [Extent1].[StartTime] AS [StartTime], 
    [Extent1].[PreEndTime] AS [PreEndTime], 
    [Extent1].[EndTime] AS [EndTime], 
    [Extent1].[Status] AS [Status], 
    [Extent1].[CameraId] AS [CameraId], 
    [Extent1].[DomainId] AS [DomainId], 
    [Extent1].[CreateDateTime] AS [CreateDateTime], 
    [Extent1].[CreateUserId] AS [CreateUserId], 
    [Extent1].[LastUpdateDateTime] AS [LastUpdateDateTime], 
    [Extent1].[LastUpdateUserId] AS [LastUpdateUserId], 
    [Extent1].[IsDeleted] AS [IsDeleted], 
    [Extent1].[IsEnabled] AS [IsEnabled]
    FROM [dbo].[Devices] AS [Extent1]

其他同样的方法:

SELECT 
    [Extent1].[Id] AS [Id], 
    [Extent1].[FirmwareSetName] AS [FirmwareSetName], 
    [Extent1].[CreateDateTime] AS [CreateDateTime], 
    [Extent1].[CreateUserId] AS [CreateUserId], 
    [Extent1].[LastUpdateDateTime] AS [LastUpdateDateTime], 
    [Extent1].[LastUpdateUserId] AS [LastUpdateUserId], 
    [Extent1].[IsDeleted] AS [IsDeleted], 
    [Extent1].[IsEnabled] AS [IsEnabled]
    FROM [dbo].[FirmwareSets] AS [Extent1]
    WHERE [Extent1].[Id] = @EntityKeyValue1
-- EntityKeyValue1: '6c36fddf-d3d9-416b-84df-cd849006eef1' (Type = Guid, IsNullable = false)
阅读 5.1k
2 个回答

把参数换成Expression<Func<T, bool>>
public virtual IEnumerable<T> GetModels(Expression<Func<T, bool>> exp)

如果参数是Func<T, bool>,则查询所有数据,筛选是在内存中进行的。
Expression<Func<T, bool>> 筛选是在数据库中进行的。

新手上路,请多包涵

public IList<Device> GetDeviceByNodeId(string nodeId)

        => EntitySet.Where(device => device.DeviceNodeId == nodeId).ToList();

把封装去掉试试,你这个写法应该是把相关数据读到内存里,然后执行linq where

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进