【问题标题】:Entity Framework: Unable to call stored procedure, wrong code generation实体框架:无法调用存储过程,错误代码生成
【发布时间】:2014-01-14 17:43:00
【问题描述】:

我有一个有效的存储过程,当从旧的 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 吗?如果没有,我怎样才能让它产生更好的东西?

【问题讨论】:

  • 研究在 SqlConnection 和 SqlCommand 对象周围使用“using()”

标签: c# entity-framework stored-procedures


【解决方案1】:

在我看来是正确的。因为您可以有多个输出,并且 C# 函数不能返回多个内容,所以它在 ObjectParameter 中返回输出。我相信这是它生成它的唯一方法。如果生成函数调用而不是SP调用,可能会生成返回类型为字符串的(我没试过),但这是为了支持多个输出参数。如果你愿意,你可以用你自己的函数包装这个生成的函数,调用这个函数并返回 parentID 参数值。

private string GetParentId(string appId)
{
   ObjectParameter parentID = new ObjectParameter("ParentID", typeof(string));
   GetParentID(appId, parentID);
   return parentID.Value.ToString();
}

【讨论】:

  • 谢谢,但如何使用 OutputParameter 代码?你能告诉我一些代码来从中取出 parentId 吗?
  • 已更新 - 类似的东西。
  • 在返回 parentID.Value 时它是一个对象。我只是返回 parentId.Value.ToString() 吗?
  • 是的 - 您可能需要进行空值检查。
猜你喜欢
  • 1970-01-01
  • 2011-10-11
  • 1970-01-01
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多