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

查看:164
本文介绍了c# - 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)

解决方案

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

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

这篇关于c# - Entity Framework使用Where方法查询单行记录,但生成的SQL语句没有Where子句是为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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