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?
We add a new Standard entity and Student entity and save them to the database using the SaveChanges() method. This will create a new transaction and execute INSERT commands for Standard and Student entities within a transaction and commit them. After this, we add a new Course entity and call SaveChanges() .
This feature was introduced in EF Core 5.0. When SaveChanges is invoked and a transaction is already in progress on the context, EF automatically creates a savepoint before saving any data. Savepoints are points within a database transaction which may later be rolled back to, if an error occurs or for any other reason.
Entity Framework internally maintains transactions when the SaveChanges() method is called. It means the Entity Framework maintains a transaction for the multiple entity insert, update and delete in a single SaveChanges() method.
What EF does by default. In all versions of Entity Framework, whenever you execute SaveChanges() to insert, update or delete on the database the framework will wrap that operation in a transaction. This transaction lasts only long enough to execute the operation and then completes.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With