【问题标题】:EntityFramework and sp_executesqlEntityFramework 和 sp_executesql
【发布时间】:2011-08-09 17:22:16
【问题描述】:

为什么当从 Entity Framework ObjectContext.ExecuteStoreCommand() 运行以下自动生成的 SQL 时,参数全部为 NULL。

exec sp_executesql 
N'SaveModel',
N'@ModelID int,@Name nvarchar(24),@Description nvarchar(34)',
@ModelID=4,
@Name=N'Status',
@Description=N'The status of a model.'

在 ExecuteStoreCommand 运行后,我从 Profiler 获取了这条 SQL,您可以看到 @ModelID 参数设置为 4,Name = 'Status',Description = 'The status of the model'。但是,在存储过程 SaveModel 中打印 ModelID 时,它为 NULL。下面是演示空参数的存储过程:

USE [Bluewater]
GO
/****** Object:  StoredProcedure [dbo].[SaveModel]    Script Date: 08/09/2011 13:15:04 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      Nicholas Barger
-- Create date: 08/07/2011
-- Description: Save model entity (create/update).
-- =============================================
ALTER PROCEDURE [dbo].[SaveModel] 
@ModelID int = null, 
@Name varchar(255) = null,
@Description varchar(1000) = null
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;

PRINT ('ModelID: ' + CAST(ISNULL(@ModelID, 0) AS VARCHAR(10)));

END

-- 发布答案--

问题是使用 ExecuteStoreCommand() 的原始调用,我认为第一个参数只请求存储过程的名称,而不是完整的存储过程语法。以下是 BROKEN 代码示例:

e.ExecuteStoreCommand("SaveModel", new SqlParameter[] { 
            new SqlParameter("ModelID", model.ModelID), 
            new SqlParameter("Name", model.Name),
            new SqlParameter("Description", model.Description)
})

这是工作代码:

e.ExecuteStoreCommand("SaveModel @ModelID, @Name, @Description", new SqlParameter[] { 
            new SqlParameter("ModelID", model.ModelID), 
            new SqlParameter("Name", model.Name),
            new SqlParameter("Description", model.Description)
})

【问题讨论】:

    标签: sql entity-framework


    【解决方案1】:

    那里生成的 sql 不正确,下面的 sql 会产生您期望的结果...

    exec sp_executesql 
    N'SaveModel @ModelID, @Name, @Description',
    N'@ModelID int,@Name varchar(24),@Description varchar(34)',
    @ModelID=4,
    @Name=N'Status',
    @Description=N'The status of a model.'
    

    在我看来是这样的

    A) 实体框架中的一个错误

    B) 你的实体模型有问题

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-01
      • 1970-01-01
      相关资源
      最近更新 更多