我有一个工作存储过程,当从旧的 ADO.NET 调用时该过程可以工作。以下是:
GO
ALTER procedure [dbo].[GetParentID]
@SSHIP_AppID as varchar(50),
@ParentID as varchar(150) OUTPUT
AS
BEGIN
SET NOCOUNT ON;
SELECT @ParentID = a.iBuild_GUID
FROM dbo.XRef_iBuild_SSHIP as a
WHERE a.SSHIP_appId = @SSHIP_AppID
AND a.SSHIP_appId <> ''
END
在ADO.NET中,它需要一个appID并简单地返回一个字符串parentId:
private string GetParentId(string appId)
{
var connection = new SqlConnection();
string parentId = String.Empty;
try
{
connection.ConnectionString = "Data Source="blah...";
var command = new SqlCommand("GetParentId", connection);
command.CommandType = CommandType.StoredProcedure;
command.Parameters.Add(new SqlParameter("@SSHIP_AppID", appId));
SqlParameter parent = new SqlParameter("@ParentID", SqlDbType.VarChar, 255);
parent.Direction = ParameterDirection.Output;
command.Parameters.Add(parent);
connection.Open();
command.ExecuteNonQuery();
parentId = (command.Parameters["@ParentID"].Value).ToString();
}
catch (Exception ex)
{
Logger.LogError(appId, ex.ToString(), "Interface12 - Cannot get ParentId", null, "", 0, "Interface12");
}
finally
{
connection.Close();
}
return parentId;
}
以下是当我执行存储过程的函数导入时 EF 生成的内容:
public virtual int GetParentID(string sSHIP_AppID, ObjectParameter parentID)
{
var sSHIP_AppIDParameter = sSHIP_AppID != null ?
new ObjectParameter("SSHIP_AppID", sSHIP_AppID) :
new ObjectParameter("SSHIP_AppID", typeof(string));
return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction("GetParentID", sSHIP_AppIDParameter, parentID);
}
这是正确的吗?如果是这样,我可以有一些示例代码来获取parentID吗?如果没有,我怎样才能让它产生更好的东西?
最佳答案
对我来说看起来是正确的。由于可以有多个输出,并且 C# 函数不能返回多个内容,因此它在 ObjectParameter 中返回输出。我相信这是产生它的唯一方式。如果生成函数调用而不是 SP 调用,也许它会生成返回类型为字符串的函数(我没有尝试过),但这是为了支持多个输出参数。如果您愿意,您可以用您自己的函数包装这个生成的函数,调用该函数并返回parentID 参数值。
private string GetParentId(string appId)
{
ObjectParameter parentID = new ObjectParameter("ParentID", typeof(string));
GetParentID(appId, parentID);
return parentID.Value.ToString();
}
关于c# - Entity Framework : Unable to call stored procedure,错误的代码生成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21120287/