使用的数据库:SqlServer2012
IDE:VS 2017
EF框架版本:6.4.0
存储过程
CREATE PROCEDURE p_test @id int,@returnText nvarchar(Max) output AS BEGIN DECLARE @name nvarchar(20) select @name= Name from [dbo].[party_member] where ID=@id set @returnText='姓名:'+@name END GO
调用代码(C#)
public string getText(int id) { List<SqlParameter> paramArray = new List<SqlParameter>(); paramArray.Add(new SqlParameter("@id", id)); SqlParameter p = new SqlParameter("@returnText", SqlDbType.NVarChar,30); p.Direction = ParameterDirection.Output; paramArray.Add(p); using(PAMSDBContext db = new PAMSDBContext()) { try { db.Database.ExecuteSqlCommand("exec [p_test] @id,@returnText out", paramArray.ToArray()); } catch (Exception ex) { throw; } string text = (string)paramArray[1].Value; return text; } }
需注意的是,下面这行代码,对于输出型参数,字符串必须设置长度,否则默认长度0,会报错 “String[1]: Size 属性具有无效大小值 0”
SqlParameter p = new SqlParameter("@returnText", SqlDbType.NVarChar,30);