如何在实体框架中使用交易?

lok*_*oki 10 .net c# entity-framework visual-studio-2010 visual-studio-2008

如何在Entity Framework中使用事务?我在Stackoverflow上阅读了一些链接:使用Transactions或SaveChanges(false)和AcceptAllChanges()?

但; 我有3个表,所以我有3个实体:

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);
Run Code Online (Sandbox Code Playgroud)

Personel,Prim,Finans我的桌子.如果你看Prim表你可以看到Prim值浮点值如果我写一个文本框而不是浮点值我的事务必须运行.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

cas*_*One 12

当您进行调用时SaveChanges,实体框架将在单个事务中执行这些操作.

当你使用这个TransactionScope类时,你会说"我希望在这个块中运行的东西被封装在一个更大的事务中",这确实是你所做的.

当你调用CompleteTransactionScope,就是执行提交所包含的事务所包含的所有操作的内容TransactionScope.