EntityFramework和sp_executesql

时间:2011-08-09 17:22:17

标签: sql entity-framework

为什么在从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 ='模型的状态'。但是,在存储过程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

- POST ANSWER -

问题是使用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)
})

1 个答案:

答案 0 :(得分: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)您的实体模型存在问题