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();
}
}
.SaveChanges()
on theDbContext
... so why not just loop through, make all of your inserts/updates, then call.SaveChanges()
after exiting the loop?