public ActionResult MaterialProductsGrid(MaterialProductGridModel model) { List<MaterialToProduct> mpAdd = new List<MaterialToProduct>(); List<int> mpDelete = new List<int>(); foreach (var mp in model.MaterialProducts) { if (mp.IsActive) { // we only need to add new ones since nothing will change with existing ones if (mp.MaterialToProductID == 0) { mpAdd.Add(new MaterialToProduct { ID = mp.MaterialToProductID, MaterialID = mp.MaterialID, ProductID = mp.ProductID }); } } else { // only need to delete ones that already exist in the database if (mp.MaterialToProductID > 0) { mpDelete.Add(mp.MaterialToProductID); } } } // now update the database by deleting ones and updating others using (var mm = new MaterialsManager()) { mm.DeleteMaterialToProducts(mpDelete); mm.InsertMaterialToProducts(mpAdd); } return RedirectToAction("Index"); }