3

我试图从实体框架 4.1(mvc 3 web 应用程序)调用存储过程。它没有抛出异常,但插入/更新没有发生?当我手动执行存储过程时,它可以工作。

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)
                    );                         
                }
            }
4

1 回答 1

8

尝试使用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查询。

于 2012-12-20T23:03:09.950 回答