Output parameter in stored procedure in EF
我有一个包含许多复杂存储过程的现有数据库,我想通过 EF 4 使用这些过程。我已经完成了以下操作:
结果代码:
1 2 | CustomerEntities entity = new CustomerEntities(); var result = entity.MyFunction("XYZ", ref o_MyString); |
现在我的存储过程有一个输出参数,我曾经通过 ref(在 WebForm 中)调用它。但我收到以下错误:
cannot convert from 'ref string' to
'System.Data.Objects.ObjectParameter'
请帮忙
编辑
当我尝试保存时,出现以下错误
A mapping function binding specifies a function Model.Store.P_GetCustomer with an unsupported parameter: o_MyString. Output parameters may only be mapped through the RowsAffectedParameter property. Use result bindings to return values from a function invocation.
输出参数在
1 2 3 | var oMyString = new ObjectParameter("o_MyString", typeof(string)); var result = ctx.MyFunction("XYZ", oMyString).ToList(); var data = oMyString.Value.ToString(); |
原因是函数导入不能使用ref参数,因为直到你处理来自数据库的结果集才填充输出参数=如果你不调用
msdn 建议如下:
1
2
3
4
5
6
7 CREATE PROCEDURE dbo.GetDepartmentName
@ID INT ,
@Name NVARCHAR(50) OUTPUT
AS
SELECT @Name = Name
FROM Department
WHERE DepartmentID = @ID
解决方案
1
2
3
4
5
6
7
8 using (SchoolEntities context = new SchoolEntities())
{
// name is an output parameter.
ObjectParameter name = new ObjectParameter("Name", typeof(String));
context.GetDepartmentName(1, name);
Console.WriteLine(name.Value);
}