使用实体框架4.1执行更新/插入存储过程?

时间:2012-12-20 22:23:05

标签: asp.net-mvc stored-procedures entity-framework-4.1

我试图从实体框架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)
                    );                         
                }
            }

1 个答案:

答案 0 :(得分:6)

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