实体框架-DbContextTransaction.Rollback()中的问题 [英] Entity Framework - Issues in DbContextTransaction.Rollback()

查看:154
本文介绍了实体框架-DbContextTransaction.Rollback()中的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Entity Framework 连接了数据库。我实现了一个联系人存储库以保存联系人信息(示例存储库)。在Said类文件中,我声明了一个静态属性以处理 DBEntities (即 BLabsEntities ),即 Context ,并且还声明了静态属性 > DbContextTransaction 。

I connected the database using Entity Framework. I Implemented a Contact Repository to Save the Contact Information (Sample Repository). In the Said Class file, I declared a static property for handling DBEntities (i.e., BLabsEntities) namely "Context" and also declared a static property for DbContextTransaction.

在以下代码中,我在 SaveContact中添加了一个try catch块来处理实体框架的异常。 ()存储库方法。我以上述方法启动交易,然后开始保存联系人过程,然后在数据库表 dbo.Contact中添加了例外数据。 code>按照我的想法,它抛出了例外。在Catch块中,我启动上述交易的 Rollback 进程,并试图在 ErrorLog表中插入异常消息,但是即使执行了回滚过程,Context属性也可以保留联系信息。 因此,在尝试将记录插入 dbo.ErrorLog表 时,它再次在catch块中引发Exception。我添加了调试快照供您参考。

In the following code I added a try catch block to handle Exceptions of Entity Framework in the SaveContact() Repository method. I Initiated a transaction before starting the Save Contact process in the above said method, then I added a exceptional data into the database table dbo.Contact as per my thought it thrown the exception. In the Catch block I'm initiating the Rollback process of the said transaction and I'm trying to insert the Exception message in the ErrorLog Table, but the Context property holds the Contact information even-though the Rollback process executed. So, it throwing Exception in the catch block once again while on trying to insert the record in the dbo.ErrorLog Table. I added a debugging snapshot for your reference.

C#代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;

namespace EF_Sample
{
    public class ContactRepository
    {
        private static BLabsEntities _context;
        private static DbContextTransaction _dbTransaction;

        protected static BLabsEntities Context
        {
            get { return _context ?? (_context = new BLabsEntities()); }
        }

        protected static DbContextTransaction DBTransaction
        {
            get { return _dbTransaction; }
            set { _dbTransaction = value; }
        }

        public void SaveContact(Contact contact = null)
        {
            try
            {
                if (contact == null)
                {
                    contact = new Contact()
                    {
                        FirstName = null,
                        LastName = null
                    };
                }


                BeginTransaction();
                Context.Contacts.Add(contact);
                Context.SaveChanges();
            }
            catch (Exception ex)
            {
                CommitTransaction(false);

                BeginTransaction();
                ErrorLog error = new ErrorLog()
                {
                    Message = ex.Message
                };

                Context.ErrorLogs.Add(error);

                Context.SaveChanges();
            }
            finally
            {
                CommitTransaction();
            }
        }

        private void BeginTransaction()
        {
            DBTransaction = Context.Database.BeginTransaction();
        }

        private void CommitTransaction(bool flag = true)
        {
            try
            {
                if (flag)
                {
                    DBTransaction.Commit();
                }
                else
                {
                    DBTransaction.Rollback();
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine("Error: {0}", Ex.Message);
            }
        }
    }
}

调试快照:

<$ c $中的异常c> try Block :通过代码明确创建的异常

Exception in try Block: Explicitly Created Exception by Code

捕获块中的异常: Rollback 操作失败

数据库表结构:

请协助我完成回滚操作成功清除上下文更改

Kindly assist me how to do the Rollback operation successfully to clear the Context Changes.

推荐答案

实际答案可能更简单:

https:// github.com/aspnet/EntityFramework.Docs/issues/327

在大多数情况下,不需要显式调用dbContextTransaction.Rollback(),因为将

The explicit call to dbContextTransaction.Rollback() is in most cases unnecessary, because disposing the transaction at the end of the using block will take care of rolling back.


如果SQL Server中发生足够严重的错误,则
事务将自动回滚,并且对catch块中的
dbContextTransaction.Rollback()的调用实际上将失败。

If an error of sufficient severity occurs in SQL Server, the transaction will get automatically rolled back, and the call to dbContextTransaction.Rollback() in the catch block will actually fail.

这篇关于实体框架-DbContextTransaction.Rollback()中的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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