gpt4 book ai didi

.net-core-3.0 - EF Core 3.0 中的存储过程

转载 作者:行者123 更新时间:2023-12-03 13:57:24 24 4
gpt4 key购买 nike

如何在 EF Core 3.0 中使用存储过程?

我已经尝试了以下

var user = await _context.Query<User>().FromSql("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();

var user = await _context.Query<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();

var user = await _context.Set<User>().FromSql("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();

var user = await _context.Set<User>().FromSqlRaw("EXECUTE dbo.spGeneral_Authenticate").FirstOrDefaultAsync();

EF 核心以错误的方式翻译 SQL。我从日志文件中得到了翻译后的 SQL。

2019-09-27 11:21:36.086 +05:30 [Error] Failed executing DbCommand ("30"ms) [Parameters=[""], CommandType='Text', CommandTimeout='30']" ""SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName] FROM ( EXECUTE dbo.spGeneral_Authenticate ) AS [u]" 2019-09-27 11:21:36.154 +05:30 [Error] An exception occurred while iterating over the results of a query for context type '"__________Context"'." ""Microsoft.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'EXECUTE'. Incorrect syntax near ')'.



翻译后的 SQL:
SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName]
FROM (
EXECUTE dbo.spGeneral_Authenticate
) AS [u]

最佳答案

Microsoft.Data.SqlClient.SqlException (0x80131904): Incorrect syntax near the keyword 'EXECUTE'. Incorrect syntax near ')'.



对于上述错误,我们应该使用 .ToList() 或 .ToListAsync() 而不是 .FirstOrDefault() 或 .FirstOrDefaultAsync()

它会工作
var user = await _context.Set<User>().FromSql("EXECUTE dbo.spTest").ToListAsync();

它不会工作
var user = await _context.Set<User>().FromSql("EXECUTE dbo.spTest").FirstOrDefaultAsync();
/*
Transalated SQL:
SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName]
FROM (
EXECUTE dbo.spTest
) AS [u]
*/

关于.net-core-3.0 - EF Core 3.0 中的存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58128636/

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