实体框架中的多个SaveChanges调用 [英] Multiple SaveChanges calls in entity framework

查看:135
本文介绍了实体框架中的多个SaveChanges调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在建立我自己的自定义存储库,基于实体框架,我创建了一些扩展方法,允许我将部分视图模型保存为实体模型,因此我正在构建我自己的Add和Update方法。



目前,每个方法都有调用DbContext的SaveChanges(),这意味着每个模型都会调用一个调用。



我正在为MVC4网站构建这个基本的DAL模式,这意味着大部分时间我将访问1个模型,但不一定是这种情况。



在更新ie 3实体时,为每个模型调用SaveChanges()是不是太糟糕的做法,或者我应该先将对象上下文添加到对象上下文,而不是将SaveChanges()作为某种事务提交?

解决方案

我知道这是一个迟到的答案,但我发现分享有用。



strong> EF6 使用 dbContext.Database.BeginTransaction()来更容易地实现



如下:

  (var context = new BloggingContext())
{
using(var dbContextTransaction = context.Database.BeginTransaction())
{
try
{
//做你的修改
context.SaveChanges();

//另行修改
context.SaveChanges();

dbContextTransaction.Commit();
}
catch(异常)
{
dbContextTransaction.Rollback();
}
}
}

有关更多信息,请参阅< a href =http://msdn.microsoft.com/en-us/data/dn456843>此



再次在EF6向前


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.

Currently, each method has SaveChanges() from DbContext called at the end which means for every model, one call will be invoked.

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.

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.

Now in EF6 it's easier to acheeve this by using dbContext.Database.BeginTransaction()

like this :

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)
        {
            dbContextTransaction.Rollback();
        }
    }
}

for more information look at this

again it's in EF6 Onwards

这篇关于实体框架中的多个SaveChanges调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆