gpt4 book ai didi

entity-framework - 为什么 SQL 中 SingleOrDefault 结果为 TOP(2)?

转载 作者:行者123 更新时间:2023-12-03 02:16:40 25 4
gpt4 key购买 nike

我使用的是EF4.0,我写了一个查询:

var query = context.Post.Where(p => p.Id == postId).SingleOrDefault();

我只需要此查询中的一篇文章。我以为 SingleOrDefault() 会生成“SELECT TOP(1) ...”,但是当我查看 SQL Profiler 时,它是:

exec sp_executesql N'SELECT TOP (2) 
[Extent1].[Id] AS [Id],
[Extent1].[Title] AS [Title],
[Extent1].[Slug] AS [Slug],
[Extent1].[PubDate] AS [PubDate],
[Extent1].[PostContent] AS [PostContent],
[Extent1].[Author] AS [Author],
[Extent1].[CommentEnabled] AS [CommentEnabled],
[Extent1].[AttachmentId] AS [AttachmentId],
[Extent1].[IsPublished] AS [IsPublished],
[Extent1].[Hits] AS [Hits],
[Extent1].[CategoryId] AS [CategoryId]
FROM [dbo].[Post] AS [Extent1]
WHERE [Extent1].[Id] = @p__linq__0',N'@p__linq__0 uniqueidentifier',@p__linq__0='ECD9F3BE-3CA9-462E-AE79-2B28C8A16E32'

我想知道为什么 EF 结果是 SELECT TOP (2)?我只需要一篇文章。

最佳答案

它选择 top 2,这样如果数据库中实际上有 2 条或多于 2 条记录,则会抛出异常。如果它只选择前 1 个,则不会出错。

关于entity-framework - 为什么 SQL 中 SingleOrDefault 结果为 TOP(2)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11839123/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com