Entity Framework 6 中存储过程的执行是否需要调用 SaveChanges?

Mat*_*277 6 c# stored-procedures entity-framework

我对在实体框架中调用存储过程有疑问。我有这个代码:

using (var context = new DbContext("test"))
{
    context.Database.ExecuteSqlCommand("SomeStoredProcedure");
    context.SaveChanges();
}
Run Code Online (Sandbox Code Playgroud)

我是否需要SaveChanges直接调用方法(如本例所示)还是该事务会自动提交?

Ger*_*old 5

SaveChanges基本上将上下文的更改跟踪器中的更改与数据存储同步。当您通过上下文本身调用存储过程时,context.Database.ExecuteSqlCommand它完全忽略存储过程可能已应用于数据库的任何更改,因此SaveChanges不会提交任何这些更改。它们已经提交(假设存储过程修改数据)。

您的根本问题似乎是如何在一个事务中提交所有更改(来自存储过程和 SaveChanges)。如果这就是您想要的,您可以将代码包装在TransactionScope

using (var ts = new System.Transactions.TransactionScope())
{
    using (var context = new DbContext("test"))
    {
        ... // more code here
        context.Database.ExecuteSqlCommand("SomeStoredProcedure");
        context.SaveChanges();
    }
    ts.Complete();
}
Run Code Online (Sandbox Code Playgroud)


Mat*_*and 4

SaveChanges()调用后不需要该命令ExecuteSqlCommand()。但是,请注意,在重新加载实体之前,上下文不会知道该调用期间发生的更改。

https://msdn.microsoft.com/en-us/data/jj592907.aspx