实体框架中的多个 SaveChanges 调用 [英] Multiple SaveChanges calls in entity framework
问题描述
我正在基于实体框架构建自己的自定义存储库,并且正在创建一些扩展方法,这些方法允许我将部分视图模型保存为实体模型,因此我正在构建自己的 Add 和 Update 方法.
I am building my own custom repository, based on entity framework, and I'm creating some extension methods that allow me to save partial view models as entity models so I'm building my own Add and Update methods.
目前,每个方法都在最后调用了来自 DbContext 的 SaveChanges(),这意味着对于每个模型,都会调用一个调用.
Currently, each method has SaveChanges() from DbContext called at the end which means for every model, one call will be invoked.
我正在为 MVC4 站点构建这个基本的 DAL 模式,这意味着大部分时间我将访问 1 个模型,但并非必须如此.
I'm building this base DAL pattern for MVC4 sites which means most of the time I will access 1 model, but it does not have to be the case though.
在更新时为每个模型调用 SaveChanges() 是不是太糟糕了,即 3 个实体,还是我应该首先将所有内容添加到对象上下文而不是 SaveChanges() 作为某种事务提交?
Is it too bad practice to call SaveChanges() for each model when updating i.e. 3 entities or should I add everything first to object context and than do SaveChanges() as some sort of transaction commit?
推荐答案
我知道这有点晚了,但我发现分享它很有用.
I know it's kind of late answer but i found it useful to share.
现在在 EF6 中使用 dbContext.Database.BeginTransaction()
像这样:
using (var context = new BloggingContext())
{
using (var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
// do your changes
context.SaveChanges();
// do another changes
context.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception ex)
{
//Log, handle or absorbe I don't care ^_^
}
}
}
有关详细信息,请查看this
它再次出现在 EF6 Onwards
这篇关于实体框架中的多个 SaveChanges 调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!