Как применить транзакцию в Entity Framework - PullRequest
6 голосов
/ 08 июня 2011

У меня есть две таблицы.Я обновляю эти таблицы, используя платформу сущностей.вот мой код

public bool UpdateTables()
{
      UpdateTable1();
      UpdateTable2();
}

Если какая-либо операция по обновлению таблицы завершается неудачно, другие не должны быть зафиксированы, как мне добиться этого в рамках сущности?

Ответы [ 4 ]

14 голосов
/ 08 июня 2011
using (TransactionScope transaction = new TransactionScope())
{
    bool success = false;
    try
    {
        //your code here
        UpdateTable1();
        UpdateTable2();
        transaction.Complete();
        success = true;
    }
    catch (Exception ex)
    {
        // Handle errors and deadlocks here and retry if needed.
        // Allow an UpdateException to pass through and 
        // retry, otherwise stop the execution.
        if (ex.GetType() != typeof(UpdateException))
        {
            Console.WriteLine("An error occured. "
                + "The operation cannot be retried."
                + ex.Message);
            break;
        }
    }    

    if (success)
        context.AcceptAllChanges();
    else    
        Console.WriteLine("The operation could not be completed");

    // Dispose the object context.
    context.Dispose();    
}
4 голосов
/ 08 июня 2011

используйте транзакции

   public bool UpdateTables()
    {
        using (System.Transactions.TransactionScope sp = new System.Transactions.TransactionScope())
        {
            UpdateTable1();
            UpdateTable2();
            sp.Complete();
        }
    }

, также вам нужно добавить System.Transactions в ссылку вашего проекта

0 голосов
/ 16 сентября 2012

Вы можете сделать что-то вроде этого ...

using (TransactionScope ts = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.RepeatableRead }))
                {
                    using (YeagerTechEntities DbContext = new YeagerTechEntities())
                    {
                        Category category = new Category();

                        category.CategoryID = cat.CategoryID;
                        category.Description = cat.Description;

                        // more entities here with updates/inserts
                        // the DbContext.SaveChanges method will save all the entities in their corresponding EntityState

                        DbContext.Entry(category).State = EntityState.Modified;
                        DbContext.SaveChanges();

                        ts.Complete();
                    }
                }
0 голосов
/ 16 июля 2012

Вам не нужно использовать TransactionScope: Entity Framework автоматически применяет транзакцию при вызове SaveChanges () в вашем контексте.

public bool UpdateTables()
{
    using(var context = new MyDBContext())
    {
        // use context to UpdateTable1();
        // use context to UpdateTable2();

        context.SaveChanges();
    } 
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...