如何使用实体框架执行存储过程并从存储过程获得输出

本文关键字:存储过程 输出 实体 框架 执行 何使用 | 更新日期: 2023-09-27 18:05:58

我一直试图通过调用存储过程来插入使用EF6的记录,并试图从存储过程中获得输出,这是新创建的ID,但不断遇到砖墙。

我有一个存储过程,它的OUTPUT是ContactID

CREATE PROCEDURE [dbo].[usp_InsertContact]
    @ContactID int output,
    @Name nvarchar(50)
AS
insert into [Contact]
    (Name) values (@Name)
    set @ContactID = @@IDENTITY

我正在调用存储过程并像这样传递值…

return Convert.ToInt32(AWJE.Database.SqlQuery<int>
   ("usp_InsertContact @Name", contact.Name));

没有工作,我得到了以下错误…(我之前贴过这个,我自己也回答过,但它不起作用)。

System.Data.Entity.Infrastructure.DbRawSqlQuery ' 1(系统。[Int32]'输入'系统。IConvertible误差

然后我去试试这个…

return AWJE.Database.ExecuteSqlCommand
    ("exec usp_InsertContact @Name", contact.Name);

当它被调用时,我得到以下错误…

附加信息:必须声明标量变量"@Name"。

如您所见,变量@Name在存储过程中,我传递的是变量@Name。

然后我尝试了这个

return AWJE.Database.ExecuteSqlCommand
   ("exec usp_InsertContact @ContactID OUTPUT, @Name", contact.Name);

这就给出了这个错误…

附加信息:必须声明标量变量"@ContactID"。

我有点迷失了如何做到这一点,我知道如何严格使用ADO.NET来做到这一点。我已经四处寻找答案,但不理解我所看到的例子,因为我所看到的例子正在与SqlParameter混合。div添加等…

而不是给你如何一步一步做的深入描述。T

这里基本上有两种方法直接对EF执行此操作,另一种方法仅使用纯SQL。

在EF中,您必须将您的进程添加为函数,这里有一篇关于如何做的文章https://msdn.microsoft.com/en-us/data/gg699321.aspx

或者像这样的纯SQL方式

SqlParameter p1= new SqlParameter("@p1", "Test");
SqlParameter p2 = new SqlParameter("@p2", "Test2");
//Executing the stored procedure from your database context
context.Database.ExecuteSqlCommand("sp_StoredProc @p1, @p2", p1, p2);

如何使用实体框架执行存储过程并从存储过程获得输出

试试

using (ConEntities context = new ConEntities())
    {
    // ContactID is an output parameter.
    ObjectParameter ContactID = new ObjectParameter("ContactID", typeof(int));
    SqlParameter Name = new SqlParameter("@Name", "hello sir");
    context.usp_InsertContact(ContactID, Name);
    //Console.WriteLine(ContactID.Value); 
    }

我们也可以这样做

var parameters = new[] { 
        new SqlParameter("@0", SqlDbType.Int32) { Direction = ParameterDirection.Output }, 
        new SqlParameter("@1", "MY Name")
    };
    context.ExecuteStoreCommand("exec usp_InsertContact @ContactID =@0 output, @Name =@1", parameters);
    int d = (int)parameters[0].Value;

我是这样做的

   var outputId = new SqlParameter { ParameterName = "outputId", Value = 0, Direction = System.Data.ParameterDirection.Output };
    Database.ExecuteSqlCommand(
        @"spProcedureName @p1, @outputId out",
        new SqlParameter("p1", HttpContext.Current.User.Identity.Name),
        outputId
    );
   return Convert.ToInt32(outputId.Value);