In Entity Framework, how do you utilize transactions?

.net c# entity-framework visual-studio-2008 visual-studio-2010

Question

How may Entity Framework transactions be used? On Stackoverflow, I read the following links: Using Transactions or AcceptAllChanges() and SaveChanges(false)?

But I have three tables and three entities:

CREATE TABLE Personel 
(PersonelID integer PRIMARY KEY identity not null, 
Ad varchar(30), 
Soyad varchar(30),
Meslek varchar(100),
DogumTarihi datetime,
DogumYeri nvarchar(100),
PirimToplamı float);

Go

create TABLE Prim
(PrimID integer PRIMARY KEY identity not null,
PersonelID integer Foreign KEY references Personel(PersonelID),
SatisTutari int,
Prim float,
SatisTarihi Datetime);

Go

CREATE TABLE Finans 
(ID integer PRIMARY KEY identity not null, 
Tutar float);

Personnel, prim, and finances for my tables Look at the Prim table to ensure that the Prim value is a float value; otherwise, my transaction would fail.

using (TestEntities testCtx = new TestEntities())
{
    using (TransactionScope scope = new TransactionScope())
    {
       // do something...
       testCtx.Personel.SaveChanges();
       // do something...
       testCtx.Prim.SaveChanges();
       // do something...
       testCtx.Finans.SaveChanges();
       scope.Complete();
       success = true;
    }
}

How can I go about doing that?

1
10
5/23/2017 12:30:46 PM

Accepted Answer

The Entity Framework will carry out those activities in a single transaction when you call SaveChanges.

By using the TransactionScope class, you are effectively stating "I want what executes in this block to be contained in a bigger transaction."

Calling Complete on theTransactionScope , which is what commits each activity included inside the transaction as stated by theTransactionScope .

12
10/21/2016 5:03:09 AM

Popular Answer

SaveChanges operates within a transaction. SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.

from zzz-7 to zzz



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow