Stored Procedures in EF Core 3.0

情到浓时终转凉″ 提交于 2019-12-13 01:18:59

问题


How to use stored procedures in EF Core 3.0 ?

I have tried the following

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 core translating the SQL in wrong way. I got the translated SQL from log file.

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 ')'.

Translated SQL:

SELECT TOP(1) [u].[FullName], [u].[Password], [u].[UserName]
FROM (
    EXECUTE dbo.spGeneral_Authenticate
) AS [u]

回答1:


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

For the above error, we should use .ToList() or .ToListAsync() not .FirstOrDefault() or .FirstOrDefaultAsync()

It will work

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

It won't work

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]
*/


来源:https://stackoverflow.com/questions/58128636/stored-procedures-in-ef-core-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!