alekoo73
alekoo73

Reputation: 925

Entity Framework.Is it possible and recommended to use transaction within context multiple times.?

E.g. I have such code

using (AccountingEntities ent = new AccountingEntities())
{
    //just to read record
    var recs = ent.Payments.Where(pp => pp.PaymentId == 123);

    foreach (p in recs)
    {
        if (p.Status == 1)
        {
            using (var dbContextTransaction = ent.Database.BeginTransaction())
            {
                var someotherrecs = ent.SomeTable.Where(s => s.PaymentId == 456);
                foreach (var rec in someotherrecs)
                {
                    rec.Status = 2;
                }
                ent.SaveChanges();
                dbContextTransaction.Commit();
            }
        }
    }
}

If i don't have to change records I will avoid starting transaction,may be in 90% of all cases.Is it OK to do such things (starting and finishing multiple transactions within single context) ?

Upvotes: 0

Views: 161

Answers (1)

Sergey M
Sergey M

Reputation: 169

As @Ivan Stoev mentioned in a comment you don't need a transaction here at all. Read documentation https://learn.microsoft.com/ru-ru/dotnet/api/system.data.objects.objectcontext.savechanges?view=netframework-4.8

and find there:

SaveChanges operates within a transaction.

So, EF has a changetracker wich tracks any changes to entities. When you perform SaveChanges then in a single transaction all changes will be commited or rolled back in case of exception.

So your code may looks like:

using (AccountingEntities ent = new AccountingEntities())
{
    //just to read record
    var recs = ent.Payments.Where(pp => pp.PaymentId == 123);

    foreach (p in recs)
    {
        if (p.Status == 1)
        {
                var someotherrecs = ent.SomeTable.Where(s => s.PaymentId == 456);
                foreach (var rec in someotherrecs)
                {
                    rec.Status = 2;
                }
                ent.SaveChanges();

        }
    }
}

Upvotes: 1

Related Questions