我尝试从实体框架4.1(MVC 3 Web应用程序)调用存储过程。它没有引发例外,但是插入/更新没有发生?当我手动执行存储的proc时,它可以正常工作。
CREATE PROCEDURE [dbo].[SP_AddUpdateResponse]
@QuestionID int,
@UserID int,
@AnswerValue nvarchar(2000),
@ReviewID int
AS
MERGE [dbo].[Responses] AS [Target]
USING (SELECT @QuestionID, @UserID, @AnswerValue, @ReviewID)
AS [Source] ([QuestionID], [UserID], [AnswerValue], [ReviewID] )
ON [Target].[QuestionID] = [Source].[QuestionID]
AND [Target].[ReviewID] = [Source].[ReviewID]
WHEN MATCHED THEN
UPDATE SET [AnswerValue] = [Source].[AnswerValue]
WHEN NOT MATCHED THEN
INSERT ( [QuestionID], [UserID], [AnswerValue], [ReviewID] )
VALUES ( [Source].[QuestionID], [Source].[UserID],
[Source].[AnswerValue], [Source].[ReviewID] );
调用该过程的代码:
using System.Data.SqlClient;
using System.Data.Metadata.Edm;
using (var db = new NexGenContext())
{
foreach (var key in formCollection.AllKeys)
{
var answer = formCollection[key];
int questionId = Convert.ToInt32(key);
db.Database.SqlQuery<EntityType>(
"EXEC SP_AddUpdateResponse @QuestionID, @UserID, @AnswerValue, @ReviewID",
new SqlParameter("@QuestionID", questionId),
new SqlParameter("@UserID", 9999),
new SqlParameter("@AnswerValue", answer),
new SqlParameter("@ReviewID", id)
);
}
}
尝试使用ExecuteSqlCommand
而不是SqlQuery
db.Database.ExecuteSqlCommand(
"EXEC SP_AddUpdateResponse @QuestionID, @UserID, @AnswerValue, @ReviewID",
new SqlParameter("@QuestionID", questionId),
new SqlParameter("@UserID", 9999),
new SqlParameter("@AnswerValue", answer),
new SqlParameter("@ReviewID", id)
);
在SqlQuery
方法的描述中说:"使用返回由上下文跟踪的实体的方法",因此您只能将其用于SELECT
查询。