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

发布于 2022-09-02 19:39:09 字数 2107 浏览 17 评论 0

在使用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)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

表情可笑 2022-09-09 19:39:09

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

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

自此以后,行同陌路 2022-09-09 19:39:09

public IList<Device> GetDeviceByNodeId(string nodeId)

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文