[英]How to execute stored procedure and get output from the stored procedure using Entity Framework
我一直在尝试通过调用存储过程并使用EF6插入一条记录,并尝试从该存储过程中获取输出,该存储过程是新创建的ID,但仍会碰壁。
我有一个存储过程,其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 [System.Int32]'键入“ System.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.Add等混合在一起...
而不是给您逐步介绍的详细说明。 Ť
基本上,有两种直接在EF上执行此操作的方法,另一种仅使用纯SQL。
在EF中,您必须将sproc作为函数添加,此处是有关如何执行此操作的文章https://msdn.microsoft.com/zh-cn/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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.