2011-10-12 54 views
0

我使用LINQ到实体(C#的WinForms)和我的数据库结构如下建议的方法: enter image description here在数据库回滚

所有的拳头,我在表中插入新记录“creditos”,因为所有的表需要知道这张表的PK。我用的方法与像这样

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。所以这里的问题是:如果其中一个插入失败,我该如何进行回滚?假设我已经在两个表中插入了记录,但是它没有在第三个表中插入,我该如何删除所有更改?

回答

2

您可以在一个事务中包装你的所有数据库操作。如果发生任何事情,您只需不提交事务,所有事情都会回滚。实体框架数据库操作将参与事务,并且在调用事务的提交方法之前不会落实。

另外,如果你有你的实体映射正确,那么你可以在代码中指定的关系和框架,将解决外来键为您服务。这意味着你可以写

cred.Persons.Add(person); 
cred.Addresses.Add(address); 

框架知道这些对象关系映射到数据库关系,涉及映射的外键。该依存度将先插入(在你的情况下,creditos表),那么标识值将被检索,然后将相关表格将使用关系进行更新。

你可以做到这一切在一个单一的SaveChanges电话。

+0

如果所有实体正确映射(像你解释一下),我称之为单一的SaveChanges,但一些插入失败,将SaveChanges方法处理回滚操作? –

+0

默认情况下,它会创建一个事务,这意味着它会在失败时回滚。检查更多的这样的问题:http://stackoverflow.com/questions/815586/entity-framework-using-transactions-or-savechangesfalse-and-acceptallchanges –

+0

感谢的人,我今天新学到了一些东西! –

1

为了实现交易范围的功能,我相信你想要什么TransactionScope的。它配备了几个注意事项http://simpleverse.wordpress.com/2008/08/05/using-transactionscope-for-handling-transactions/

try 
    { 
     using (System.Transactions.TransactionScope scop = new System.Transactions.TransactionScope()) 
     { 
      using (NorthwindEntities entity = new NorthwindEntities()) 
      { 
       foreach (Order order in orders) 
       { 
        entity.AddToOrders(order); 
       } 
       entity.SaveChanges(); 
      } 
      scop.Complete(); 
     } 
    } 
    catch (Exception ex) 
    { 
     throw ex; 
    } 
+0

感谢杰里米我感谢你的帮助 –