2

I want to create a function that accepts a list of objects with their properties already set and does a batch update or insert on them only making 1 call to the database.

(UPDATE) Here is the working version:

    public static void BatchInsertProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            context.Products.AddRange(productList);
            context.SaveChanges();
        }
    }

This is my attempt at doing either and update or an insert on several items based on the Id. I don't think I can use AddRange here so I tried it this way and I am getting an error:

    public static void SaveMultipleProducts(IList<Product> productList)
    {
        using (var context = new DbContext())
        {
            foreach (Account p in productList)
            {
                if (p.ID == 0)
                {
                    context.Entry(p).State = EntityState.Added;
                    p.InsertUserId = "jtunney";
                    p.InsertDate = DateTime.Now;
                }
                else
                {
                    context.Entry(p).State = EntityState.Modified;
                    p.UpdateUserId = "jtunney";
                    p.UpdateDate = DateTime.Now;
                }
            }
            context.SaveChanges();
        }
    }
7
  • Are modifying in your productList the same properties for all objects with the same values?
    – Marc Cals
    Jun 9, 2015 at 17:24
  • In some cases all of the values would be the same, but in others all of the values could be different. Lets say I create a simple productList and add 3 products to it with different prices then pass it to my BulkInsert function. Can linq do this operation? Or will I have to create a long string and pass it directly to the database using the Database.SqlQuery function?
    – JTunney
    Jun 9, 2015 at 17:26
  • Why do you want to do it in Batch?
    – Marc Cals
    Jun 9, 2015 at 17:28
  • Lets say the productList has 100 items in it. In my BLL I will be looping through my productList and calling productDAL.Save(product) 100 times which makes 100 calls to the database. If I can do it in bulk it will only make 1 call. Whether its by generating a huge sql string using stringbuilder or using linq to somehow do it.
    – JTunney
    Jun 9, 2015 at 17:30
  • The database call shouldn't happen until you call .SaveChanges() on the DbContext... so why not just loop through, make all of your inserts/updates, then call .SaveChanges() after exiting the loop?
    – danludwig
    Jun 9, 2015 at 17:40

3 Answers 3

3

Removed foreach loop, changed IList<Product> to IEnumerable<Product>:

public static void BatchInsertProducts(IEnumerable<Product> productList)
{
    using (var context = new DbContext())
    {
        context.Products.AddRange(productList);
        context.SaveChanges();
    }
}

One way to do save multiple:

public static void SaveMultipleProducts(IEnumerable<Product> productList)
{
    using (var context = new DbContext())
    {
        foreach (Account p in productList)
        {
            p.InsertUserId="jtunney";
            p.InsertDate=DateTime.Now;
            context.Entry(p).State=p.Id==0?EntityState.Added:EntityState.Modified;
        }
        context.SaveChanges();
    }
}

Another way:

public static void SaveMultipleProducts(IList<Product> productList)
{
    using (var context = new DbContext())
    {
        foreach (Account p in productList)
        {
            p.InsertUserId="jtunney";
            p.InsertDate=DateTime.Now;
        }
        // Add all records
        context.Products.AddRange(productList);

        // Handle updates
        foreach(var p in productList.Where(p=>p.id!=0))
        {
          context.Entry(p).State=EntityState.Modified;
        }
        context.SaveChanges();
    }
}
5
  • Good catch! can't believe I left that in there, its been a long day. By any chance do you know if this will automatically handle either updating or inserting? Lets say some objects in the list have Ids and others don't.
    – JTunney
    Jun 9, 2015 at 18:25
  • Any chance you can check my latest update and let me know if something like this is possible calling only 1 SaveChanges.
    – JTunney
    Jun 9, 2015 at 18:36
  • Really should be creating a new question without changing it, otherwise others won't be able to learn from your original question, but updating my answer. Jun 9, 2015 at 18:42
  • Actually looking at your original code, I think it should have worked. What error were you getting? Jun 9, 2015 at 18:58
  • Errr.. Actually yes my original code works and so do both of your examples. When I was creating my test list I was adding products with IDs of 997, 998, and 1000. The products with IDs 997 and 998 already existed and the one with 1000 does not. I am pretty sure for the new one I just need to not set an ID.
    – JTunney
    Jun 9, 2015 at 19:35
1

It's not necessary to call Save method for each product. If you get the products and save with the same DbContext you only have to call Save one time, then It will save all your modifications.

Imagine

List<Product> products = Context.Product.ToList();

foreach(var product in products)
{
     product.Price = new Random().Next();
}

Context.Product.SaveChanges();

This code is modifying the price for all Products in the list, but thanks to the fact that we are using the same context to retrieve the results and that EF implements Tracking to save the modifications with one call to SaveChanges it's enough.

For bulkInserts

Use AddRange method from Entity Framework http://www.entityframeworktutorial.net/EntityFramework6/addrange-removerange.aspx or you can try this library https://efbulkinsert.codeplex.com/. I have heard about it, but I have never used it

2
  • Can you check out the update I made to the function at the top of my post? Would it be something like that? I feel like my scenario is different. I am passing my function a productList that is all ready to be inserted. I don't need to make any changes within my context.
    – JTunney
    Jun 9, 2015 at 17:48
  • Add Range worked perfectly!!! Thanks so much. I figured this kind of thing would be so common that I would instantly find it with a google search. I updated my post to give others an example.
    – JTunney
    Jun 9, 2015 at 18:08
0

This is bit different approach than other....

public static DbContext BatchInsertProducts(DbContext context,IList<Product> productList)
{
    context.Configuration.AutoDetectChangesEnabled = false;
    for (int i = 0; i < lobbies.Count; i += 100)
    {
        context.Set<Product>().AddRange(lobbies.GetRange(i, Math.Min(100, lobbies.Count - i)));
        context.Products.AddRange(productList);
        context.SaveChanges();

        //Dispose and create a context
        context.Dispose();
        context = new DbContext;
        context.Configuration.AutoDetectChangesEnabled = false;   
    }

    return context;
}

The above mentioned code snippet does some additional task inorder to improve the performance and also we can specify the number of records that need to included in each batch manipulation.

If we want to insert bulk records, creating new context for each batch and dispose then once task is done. very much improve the performance (from minutes to operation to seconds)

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.