[英]How to use Transaction in Entity Framework?
How to use transactions in Entity Framework? 如何在Entity Framework中使用事务? I read some links on Stackoverflow : Using Transactions or SaveChanges(false) and AcceptAllChanges()?
我在Stackoverflow上阅读了一些链接: 使用Transactions或SaveChanges(false)和AcceptAllChanges()?
BUT; 但; i have 3 table so i have 3 entities:
我有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);
Personel, Prim, Finans my tables. Personel,Prim,Finans我的桌子。 If you look Prim table you can see Prim value float value if I write a textbox not float value my transaction must run.
如果你看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;
}
}
How can I do that? 我怎样才能做到这一点?
When you make the call to SaveChanges
, the Entity Framework will perform those operations in a single transaction. 当您调用
SaveChanges
,实体框架将在单个事务中执行这些操作。
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. 当您使用
TransactionScope
类时 ,您说“我希望在此块中运行的内容被封装在更大的事务中”,这确实是您所做的。
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
. 在
TransactionScope
上调用Complete
时,就是执行TransactionScope
定义的TransactionScope
封装的所有操作的提交。
SaveChanges operates within a transaction.
SaveChanges在交易中运作。 SaveChanges will roll back that transaction and throw an exception if any of the dirty ObjectStateEntry objects cannot be persisted.
如果无法保留任何脏的ObjectStateEntry对象,SaveChanges将回滚该事务并抛出异常。
from the documentation 来自文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.