Reputation: 309
what is the best practice to edit multiple record in MVC ? I have surf the net for while now but cant find a good answer for it.
for now my solution look like this in controller:
for (int i = 0; i < customer.Count();i++)
{
Guid id = Guid.NewGuid();
id = new Guid(customer[i]);
try
{
CustomerProduct customerProduct = customerProductRepository.GetCustomerProductByCustomeridAndProductID(id,productID);
customerProductRepository.DbContext.BeginTransaction();
customerProduct.ProductVersion = productVersionRepository.Get(productVersionId);
customerProduct = customerProductRepository.SaveOrUpdate(customerProduct);
customerProductRepository.DbContext.CommitTransaction();
TempData["toastType"] = "success";
TempData["message"] = customerProduct.Customer.Name+" is been successful updated";
}
catch
{
TempData["toastType"] = "error";
TempData["message"] = "An Error occurred, Please try again later";
customerRepository.DbContext.RollbackTransaction();
return View(model);
}
}
it is possible to rollback 10 Transaction ? if the first 5 been commit it and the six record failed to commit due to some reason. Thank you
Upvotes: 1
Views: 84
Reputation: 5137
In your CustomerProductRepository
have a AddAll/UpdateAll method which will look like below code:
public void AddAll<T>(IEnumerable<T> items) where T : class
{
Guard.ArgumentNotNull(items, "items");
foreach (var item in items)
{
Set<T>().Add(item);
}
SaveChanges();
}
SaveChanges gets called only when all items are added successfully. The DB will perform a bulk update and you will get better performance.
Upvotes: 4