0

I have question regarding Entity Framework. In my program I first fill-up my DbContext with data. Then I need to delete all the data from the tables in DB, but only if new data will be saved. If db.Savechanges() throws an exception I need my old data to still be in the tables.

My code is:

static void Main(string[] args)
        {
            PdmContext db = new PdmContext();

            FillDbContext();

            try
            {

                if (db.SaveChanges() > 0)
                {
                    using (var del = new PdmContext())
                    {
                        DeleteModel.deleteFromAllTables();
                    }
                    db.SaveChanges();
                }
            }
            catch (Exception exp)
            {
                Logger.Log("Exception (global catch));
            }
        }

I can't seem to figure this out. Anyone can help with this? :)

1
  • What does DeleteModel.deleteFromAllTables() do? And why do you need two instances of PdmContext? If you're deleting your data in a separate transaction and committing that transaction then that would certainly explain why that transaction is being committed. EF won't commit a transaction if an exception is thrown, so it seems that you're committing your deletes yourself somewhere. Commented Dec 13, 2018 at 12:56

3 Answers 3

2

You can use Transaction which will make sure to revert the operation done within the scope of it if the operation fails at some stage :

using (var scope = new TransactionScope(TransactionScopeOption.Required))
{
      using (var del = new PdmContext())
      {
          DeleteModel.deleteFromAllTables();
      }
      db.SaveChanges();

      scope.Complete();  // commits the transaction     
}

Now the changes to the database will be atomic so that it will only keep all changes or not at all. I have not included exception handling code for simplicity but due to any reason if the scope.Complete() was not being executed and control exists the transaction block without executing that the transaction will get rolled back.

Sign up to request clarification or add additional context in comments.

1 Comment

Works like a charm! Thanks a lot! :)
0

You need to use a Transaction.

see how to use that:

    using (var dbContextTransaction = PdmContext.Database.BeginTransaction())
            {
                try
                {
                   // HERE your operation insert etc.

                    PdmContext.SaveChanges();

                    dbContextTransaction.Commit(); // here, apply your operation
                }
                catch (Exception)
                {
                    dbContextTransaction.Rollback(); // here, undo your operations
                }
            }

Comments

0

You can handle such scenario with transaction management.

There is two way to handle it.

1) You can use single dbcontext for all operation instead of create multiple for single operation.

using (var context = new SchoolContext())
{

    try
    {


        context.Students.Add(new Student()
        {
            FirstName = "Rama2",
            StandardId = standard.StandardId
        });


        context.Courses.Add(new Course() { CourseName = "Computer Science" });
        context.SaveChanges();

        transaction.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        Console.WriteLine("Error occurred.");
    }
}

2) Using single DbContextTransaction object:

using (var context = new SchoolContext())
{
context.Database.Log = Console.Write;

using (DbContextTransaction transaction = context.Database.BeginTransaction())
{
    try
    {
          context.Students.Add(new Student()
        {
            FirstName = "Rama2",
            StandardId = standard.StandardId
        });


        context.SaveChanges();

        context.Courses.Add(new Course() { CourseName = "Computer Science" });
        context.SaveChanges();

        transaction.Commit();
    }
    catch (Exception ex)
    {
        transaction.Rollback();
        Console.WriteLine("Error occurred.");
    }
}
}

I hope it work for you.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.