EntityFramework and sp_executesql
Why when running the following auto-generated SQL from Entity Framework ObjectContext.ExecuteStoreCommand(), the parameters all result in 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.'
I've taken this SQL from Profiler after the ExecuteStoreCommand runs, as you can see the @ModelID param is being set to 4, Name = '开发者_开发知识库Status', Description = 'The status of the model'. However, when doing a print of ModelID in the stored procedure SaveModel, it is NULL. Here is the stored procedure demonstrating the null parameters:
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 --
The problem was the original call using ExecuteStoreCommand(), I thought the first parameter requested only the name of the stored procedure, not the full stored procedure syntax. Here is an example of BROKEN code:
e.ExecuteStoreCommand("SaveModel", new SqlParameter[] {
new SqlParameter("ModelID", model.ModelID),
new SqlParameter("Name", model.Name),
new SqlParameter("Description", model.Description)
})
And here is the WORKING code:
e.ExecuteStoreCommand("SaveModel @ModelID, @Name, @Description", new SqlParameter[] {
new SqlParameter("ModelID", model.ModelID),
new SqlParameter("Name", model.Name),
new SqlParameter("Description", model.Description)
})
The sql that is generated there is not correct, the following sql yields the result you are expecting...
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.'
Looks to me like this is either
A) A bug in Entity Framework
B) A problem with your Entity Model
精彩评论