10

How to use transactions in Entity Framework? I read some links on Stackoverflow : Using Transactions or SaveChanges(false) and AcceptAllChanges()?

BUT; i have 3 table so i have 3 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);

Personel, Prim, Finans my tables. If you look Prim table you can see Prim value float value if I write a textbox not float value my transaction must run.

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 do that?

4
  • they use 3 different context.... you are trying to save each table independently? Commented Apr 14, 2010 at 14:27
  • 2
    You already have the code, what do you need help with ? Commented Apr 14, 2010 at 14:33
  • yes i want to add 3 table but transaction i must Commented Apr 14, 2010 at 15:00
  • you already use transaction with your transaction scope Commented Apr 14, 2010 at 15:06

3 Answers 3

12

When you make the call to SaveChanges, the Entity Framework will perform those operations in a single transaction.

When you use the TransactionScope class, you are saying "I want what runs in this block to be encapsulated in a larger transaction", which is indeed what you do.

When you call Complete on the TransactionScope, that is what perform the committing of all of the operations encapsulated in the transaction defined by the TransactionScope.

Sign up to request clarification or add additional context in comments.

Comments

1

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 the documentation

Comments

0

There is a similar example in the MSDN site.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.