加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc-3 – 在Dbcontext中的.NET MVC 3回滚

发布时间:2020-12-16 09:46:31 所属栏目:asp.Net 来源:网络整理
导读:在MVC 3中,可以在调用DbContext.SaveChanges()之后回滚数据库吗? 我的实体类: public class BipEntities : DbContext{ public DbSetPage Pages { get; set; } public DbSetImageFile ImageFiles { get; set; }} 我要做的是将ImageFile记录插入数据库,然后
在MVC 3中,可以在调用DbContext.SaveChanges()之后回滚数据库吗?

我的实体类:

public class BipEntities : DbContext
{
    public DbSet<Page> Pages { get; set; }
    public DbSet<ImageFile> ImageFiles { get; set; }
}

我要做的是将ImageFile记录插入数据库,然后使用自动递增的id作为图像文件名,将图像文件保存到其他地方.
当System.IO失败时,我想回滚数据库.

BipEntities db = new BipEntities();
db.Database.Connection.Open();
DbTransaction tranx = db.Database.Connection.BeginTransaction();

ImageFile img = new ImageFile { CreatedAt = DateTime.Now };
db.ImageFiles.Add(img);
db.SaveChanges();

string filename = "img" + img.Id.ToString() + ".png";
try {
    //Works on system IO to process file
    tranx.Commit();

} Catch ( Exception) {
    tranx.Rollback();
}

db.Database.Connection.Close();

但是,上面的代码给了我这个错误信息:

EntityConnection can only be constructed with a closed DbConnection.

解决方法

您应该使用TransactionScope将DbContext包装在数据库事务中,或者使用在事务内运行的DbConnection创建DbContext:

using (var con = new SqlConnection(conStr))
{
    con.Open();
    using (var tran = con.BeginTransaction())
    {
        var img = new Image();

        using (var db = new BipEntities(con))
        {
            db.Images.AddObject(img);

            db.SaveChanges();
        }

        // Write to disk here.
        WriteStuffToDisk(stuff,img.Id);

        tran.Commit();
    }        
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读