使用EF的DbContext.ExecuteSqlCommand()进行事务期间的异常

v1n*_*ozo 2 c# sql-server entity-framework-6

使用try-catch结构我试图想象如果在事务的任何点捕获异常该怎么做.下面是一个代码示例:

try
{
   DbContext.ExecuteSqlCommand("BEGIN TRANSACTION");        //Line 1
   DBContext.ExecuteSqlCommand("Some Insertion/Deletion Goes Here"); //Line 2
   DbContext.ExecuteSqlCommand("COMMIT");                   //Line 3
}
catch(Exception)
{
}   
Run Code Online (Sandbox Code Playgroud)

如果在执行'第1行'时捕获了预测,除了警告错误之外,不必做任何事情.如果它被捕获执行第二行我不知道我是否需要尝试回滚已成功打开的事务,并且如果第三行出错则会发生同样的情况.

我应该发送回滚吗?或者通过单个方法调用将所有命令直接发送到银行?

在try-catch中有一个循环执行许多事务,如示例中的那个(我需要大量的小事务而不是一个大事务,因此我可以正确地重用SQL的'_log'文件并避免它不必要地增长).

如果任何事务出错,我只需要删除它们并告知发生了什么,但我无法将其转换为一个大事务而只是使用回滚,否则它将使日志文件增长到40GB.

Kri*_*ner 6

认为这将有所帮助:

using (var ctx = new MyDbContext())
{
    // begin a transaction in EF – note: this returns a DbContextTransaction object
    // and will open the underlying database connection if necessary
    using (var dbCtxTxn = ctx.Database.BeginTransaction())
    {
       try
       {
            // use DbContext as normal - query, update, call SaveChanges() etc. E.g.:
           ctx.Database.ExecuteSqlCommand(
               @"UPDATE MyEntity SET Processed = ‘Done’ "
               + "WHERE LastUpdated < ‘2013-03-05T16:43:00’");

           var myNewEntity = new MyEntity() { Text = @"My New Entity" };
           ctx.MyEntities.Add(myNewEntity);
           ctx.SaveChanges();

           dbCtxTxn.Commit();
       }
       catch (Exception e)
       {
           dbCtxTxn.Rollback();
       }
    } // if DbContextTransaction opened the connection then it will close it here
}
Run Code Online (Sandbox Code Playgroud)

取自:https://entityframework.codeplex.com/wikipage?title = Improduved%20Transaction%20Support

基本上它的想法是你的事务成为使用块的一部分,并在其中你有一个try/catch与实际的SQL.如果try/catch中有任何失败,它将被回滚