How use begin transaction in EF Core

Discussion of open issues, suggestions and bugs regarding Entity Framework support in ADO.NET Data providers
Post Reply
keng
Posts: 6
Joined: Wed 01 Feb 2017 02:33

How use begin transaction in EF Core

Post by keng » Sun 26 Mar 2017 14:31

Hi everybody

I try use function begin transaction but can not work
I use dotConnect for Mysql and EF Core 1.1.0
this my code :

Code: Select all

 public DbTransaction BeginTransaction()
        {
            if (null == transaction)
            {
                if (_context.Database.GetDbConnection().State != ConnectionState.Open)
                {
                    _context.Database.OpenConnection();
                }

                this.transaction = (DbTransaction) _context.Database.CurrentTransaction;
                _context.Database.UseTransaction(transaction);
            }
            return transaction;
        }
and main function

Code: Select all

using (var transaction = this._unitOfWork.BeginTransaction())
                {
                    try {
                        this._unitOfWork.OrderTypeRepository.Add(new Tbordertype
                        {
                            OrderTypeID = ordertype.OrderTypeId,
                            OrderTypeName = ordertype.OrderTypeName
                        });
                        this._unitOfWork.OrderTypeRepository.Save();
                        transaction.Commit();
                    }
                    catch (Exception) {
                        transaction.Rollback();
                    }
                }
when code complie line => this._unitOfWork.OrderTypeRepository.Save();
The database save data before commit

How to use Begin Transaction

Please help me.

Shalex
Site Admin
Posts: 9543
Joined: Thu 14 Aug 2008 12:44

Re: How use begin transaction in EF Core

Post by Shalex » Mon 27 Mar 2017 14:56

Basing on the code, generated by the EF Core template shipped with Entity Developer (the Devart EF Core Model item, *.efml), try the following approach:

Code: Select all

    using (var context = new EFModel())
    {
        context.Database.BeginTransaction();

        var dept = new Dept() { DEPTNO = 11, DNAME = "Test", LOC = "Test" };
        context.Depts.Add(dept);
        context.SaveChanges();

        context.Database.CommitTransaction(); // RollbackTransaction()
    }

Post Reply