建议的数据库回滚方法
我正在使用 linq toEntity (C# Winforms),我的数据库具有以下结构:
首先,我在表“creditos”上插入新记录,因为所有表都需要知道这张桌子。我使用类似这样的方法
Credito cred = new Credito();
cred.Producto = credito.producto;
cred.Cantidad = credito.monto_prestamo;
cred.TasaInteres = credito.tasa_interes;
,然后
context.creditos.AddObject(cred);
context.SaveChanges();
//Get the ID of the inserted record
credito.idCredito = cred.IDCredito;
使用获得的表“creditos”的 PK,我使用类似的方法将其作为 FK 插入其他表中。所以这里的问题是:如果其中一个插入失败,如何进行回滚?假设我已经在两个表中插入了记录,但在第三个表中插入失败,如何删除所有更改?
I'm using linq to entities (C# Winforms) and my database has the following structure:
Fist of all, I insert new record on table 'creditos' since all tables need to know the PK of this table. I use a method with something like this
Credito cred = new Credito();
cred.Producto = credito.producto;
cred.Cantidad = credito.monto_prestamo;
cred.TasaInteres = credito.tasa_interes;
and then
context.creditos.AddObject(cred);
context.SaveChanges();
//Get the ID of the inserted record
credito.idCredito = cred.IDCredito;
With the obtained PK of table 'creditos', I insert this as a FK in the other tables using similar methods. So the question here is: how do I make a rollback if one of the insertions fails? Suppose I have already inserted records in two tables but it fails to insert in the third one, how do I delete all changes?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以将所有数据库操作包装在事务中。如果发生任何事情,您只需不提交事务,所有内容都会回滚。实体框架数据库操作将参与事务,并且在您调用事务的 commit 方法之前不会提交。
或者,如果您的实体映射正确,那么您可以在代码中指定关系,框架将为您解析外键。这意味着您可以编写
框架理解这些对象关系映射到数据库关系,其中涉及映射的外键。将首先插入依赖项(在您的情况下为 Creditos 表),然后将检索标识值,然后将使用该关系更新相关表。
您可以通过一次
SaveChanges
调用来完成这一切。You can wrap all your database operations in a transaction. If anything 'happens', you simply don't commit the transaction and everything will be rolled back. Entity Framework database operations will participate in the transaction and are not committed until you call the transaction's commit method.
Alternatively, if you have your entities mapped correctly then you can specify the relationship in code and the framework will resolve the foreign keys for you. This means that you can write
The framework understands that these object relationships map to database relationships, which involve mapped foreign keys. The dependency will be inserted first (in your case, the
creditos
table), then identity value will be retrieved, and then the related tables will be updated using that relationship.You can do this all in a single
SaveChanges
call.要实现事务范围功能,我相信您想要的是TransactionScope。它带有一些警告 http://simpleverse。 wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/
To achieve transaction scope functionality, I believe what you want is the TransactionScope. It comes with a few caveats http://simpleverse.wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/