Database Context save if valid

entity framework validation before savechanges
dbentityvalidationexception
dbupdateexception
entity framework detect changes before save
entity framework savechanges example
db.savechanges() exception
entity framework exception handling best practices
db.savechanges() return value

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? :)

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.

DbContext.SaveChanges Method (System.Data.Entity), 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  This usually indicates an optimistic concurrency violation; that is, a row has been changed in the database since it was queried. DbEntityValidationException The save was aborted because validation of entity property values failed.

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
                }
            }

Validation, A database command did not affect the expected number of rows. This usually indicates an optimistic concurrency violation; that is, a row has been changed in the  The connection to the database (including the name of the database) can be specified in several ways. If the parameterless DbContext constructor is called from a derived context, then the name of the derived context is used to find a connection string in the app.config or web.config file.

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.

Entity Framework Core – validating data and catching SQL errors , Entity Framework provides a great variety of validation features that can feed to save the new blog to the database, but MVC's client-side validation is public class BlogContext : DbContext { public DbSet<Blog> Blogs { get;  Working with DbContext. 10/23/2016; 3 minutes to read; In this article. In order to use Entity Framework to query, insert, update, and delete data using .NET objects, you first need to Create a Model which maps the entities and relationships that are defined in your model to tables in a database.

ASP.NET MVC with Entity Framework and CSS, NET Core, but can also be checked when that data is saved to the database. apply – you can't bypass them for the good reason that the database wants to keep its state valid at all times. If (Exception e, DbContext context). Modified: the entity is being tracked by the context and exists in the database, and some or all of its property values have been modified; Deleted: the entity is being tracked by the context and exists in the database, but has been marked for deletion from the database the next time SaveChanges is called

Modifying data via the DbContext, If all the files are valid, then each one is saved to disk. the code work this way to demonstrate how to manipulate the data store in the database context object. Configuring a DbContext. 10/27/2016; 5 minutes to read +8; In this article. This article shows basic patterns for configuring a DbContext via a DbContextOptions to connect to a database using a specific EF Core provider and optional behaviors.

Validate Entity in Entity Framework, When SaveChanges is called, an UPDATE statement is generated and executed by the database. var author = context.Authors.First(  At first, I had a hard time grasping the purpose and use of the save() and restore() methods of the canvas’ 2d context. It’s really very simple and here are some examples that can help you understand it better.

Comments
  • 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.
  • Works like a charm! Thanks a lot! :)