skip to Main Content

In Entity Framework 7 what would be the best way to do batchInsert to a table which is mapped using entity framework but I want to make sure that this is one transaction so either all objects are inserted or none?

THanks for hints!

3

Answers


  1. Try using a combination of Transactions & SaveChanges() method, I can share a sample code with you:

    using (var dbContext = new YourDbContext())
    {
        using (var transaction = dbContext.Database.BeginTransaction())
        {
            try
            {
                // Perform your batch insert operations here
                foreach (var entity in entitiesToInsert)
                {
                    dbContext.YourEntities.Add(entity);
                }
    
                // Save changes to the database within the transaction
                dbContext.SaveChanges();
    
                // Commit the transaction if everything is successful
                transaction.Commit();
            }
            catch (Exception ex)
            {
                // Handle exceptions and roll back the transaction if an error occurs
                transaction.Rollback();
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
    
    Login or Signup to reply.
  2. Little bit changes on @Zohair post.
    You can replace foreach loop by following statement.
    dbContext.YourEntities.AddRangeAsync(entities); //Entities will be your List or Collection.

    using (var dbContext = new YourDbContext())
    {
        using (var transaction = dbContext.Database.BeginTransaction())
        {
            try
            {
                // Perform your batch insert operations here
                dbContext.YourEntities.AddRangeAsync(entities);
    
                // Save changes to the database within the transaction
                dbContext.SaveChanges();
    
                // Commit the transaction if everything is successful
                transaction.Commit();
            }
            catch (Exception ex)
            {
                // Handle exceptions and roll back the transaction if an error occurs
                transaction.Rollback();
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    }
    
    Login or Signup to reply.
  3. There is no need having a transaction.

    using (var dbContext = new YourDbContext())
    {
       // Perform your batch insert operations here
       dbContext.YourEntities.AddRangeAsync(entities);
    
       // Save changes to the database within the transaction
       dbContext.SaveChanges();
    }
    
    1. entities should be array

    This way if something fail with any of your objects during save, everything rollsback.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search