Create a new public static method to delete existing products. Remember that, as the ProductDataAccess class is static, all its methods must also be static. To do this, paste the following code (shown in bold) inside the ProductDataAccess class.
public static void DeleteProduct(int productId) { using (var scope = new TransactionScope()) { using (SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["AdventureWorks"].ConnectionString)) { connection.Open(); var deleteProductPhotoCommand = new SqlCommand("DELETE Production.ProductPhoto WHERE ProductPhotoID NOT IN (SELECT DISTINCT ProductPhotoID FROM Production.ProductProductPhoto);", connection); deleteProductPhotoCommand.ExecuteNonQuery(); var deleteBillOfMaterials = new SqlCommand("DELETE Production.BillOfMaterials WHERE ProductAssemblyID=@ProductID OR ComponentID=@ProductID;", connection); deleteBillOfMaterials.Parameters.AddWithValue("@ProductID", productId); deleteBillOfMaterials.ExecuteNonQuery(); var relatedTables = new List<string> {"Production.ProductProductPhoto", "Production.ProductCostHistory", "Production.ProductDocument", "Production.ProductInventory", "Production.ProductListPriceHistory", "Production.ProductListPriceHistory", "Production.ProductReview", "Production.TransactionHistory", "Production.TransactionHistoryArchive", "Production.WorkOrderRouting", "Production.WorkOrder", "Sales.SalesOrderDetail", "Sales.ShoppingCartItem", "Sales.SpecialOfferProduct", "Production.Product"}; foreach (var table in relatedTables) { var deleteProductCostHistory = new SqlCommand(string.Format("DELETE {0} WHERE ProductID=@ProductID;", table), connection); deleteProductCostHistory.Parameters.AddWithValue("@ProductID", productId); deleteProductCostHistory.ExecuteNonQuery(); } scope.Complete(); } } }
FakePre-3a1f6ee5e9b443e2916d5d024cb59e89-05415d63311944a582539c74a3816e8aFakePre-279c77813ab140a5ae51c61bc8e4e292-917f52bfbd9f4ff2bc40364501b00edbFakePre-0cd991adcf9e4cdaa61c498c78d3d513-0539c54e87604279aca6442ef721e997
The preceding code creates a new transaction to perform the delete operations. First, it deletes the relation between the Products and Photo tables. Next it deletes any orphaned photos. Finally it deletes the product.