简体   繁体   English

EF Core 2使用OUTPUT参数执行存储过程

[英]EF Core 2 executing Stored Procedure with OUTPUT param

Why is the output value not getting returned? 为什么没有返回输出值?

Using EF Core 2 (2.1.0-preview-final) as the platform for managing schema through code-first modelling, I wanted to add other database objects such as SPs. 我想使用EF Core 2(2.1.0-preview-final)作为通过代码优先建模管理架构的平台,我想添加其他数据库对象,例如SP。 That was a journey itself, however the challenge under topic here is executing an SP using context.Database.ExecuteSqlCommandAsync() and retrieving the OUTPUT param value. 那本身就是一段旅程,但是这里的主题下的挑战是使用context.Database.ExecuteSqlCommandAsync()执行一个SP并获取OUTPUT参数值。

This is the code that successfully executes the SP, however the output value is never returned. 这是成功执行SP的代码,但是永远不会返回输出值。 You would think that setting the Direction of the parameter was sufficient. 您会认为设置参数的Direction就足够了。

public async Task AddAsync(Models.Filename entity)
{
    SqlParameter name = new SqlParameter("@Name", entity.Name);
    SqlParameter idOut = new SqlParameter
    {
        ParameterName = "@Id",
        SqlDbType = System.Data.SqlDbType.BigInt,
        Direction = System.Data.ParameterDirection.Output
    };
    using (var db = new MetaDataDbContext())
    {
        await db.Database.ExecuteSqlCommandAsync("[dbo].[AddFilename] @Name, @Id", name, idOut);
    }
    entity.Id = Convert.ToInt64(idOut.Value);
}

All that was needed to solve the issue was to change the T-SQL statement to be "[dbo].[AddFilename] @Name, @Id OUTPUT" 解决此问题所需要做的就是将T-SQL语句更改为"[dbo].[AddFilename] @Name, @Id OUTPUT"

EF6 - ExecuteSqlCommandAsync - Get return parameter (declare scalar variable error) looked promising however it misses a critical piece namely that the T-SQL portion must include the OUTPUT keyword for the targeted parameter. EF6- ExecuteSqlCommandAsync-获取返回参数(声明标量变量错误)看起来很有希望,但是它错过了一个关键部分,即T-SQL部分必须包括目标参数的OUTPUT关键字。

Why does EF Core always return -1 with this stored procedure? 为什么EF Core总是使用此存储过程返回-1? , in hindsight offers the solution, however it's name (title) didn't come up in my search results. ,后见之明提供了解决方案,但是我的搜索结果中没有出现名称(标题)。

HTH! HTH!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM