I'm using Asp.Net MVC and building an E-commerce application.
I've 4 tables in my DB
Product which have ProductId(PK), Name, Price, StoreId(FK)
Store which have StoreId(PK), Name, CreatedOn
Order which have OrderId(PK), StoreId(FK), OrderDate, OrderTotal
OrderDetail which have OrderDetailId(PK), OrderId(FK), Quantity, UnitPrice, Weight
When I Try to delete a single product, it doesn't give any error and deleted the product, If I delete Order record it gives an error of OrderDetails foreign key, I know I have to delete OrderDetail record first then Order record.
My scenario is, Store has multiple products, Each store has orders then order details.
Now, I don't want to delete single record every time because it takes alot of time. I want to delete a STORE and all the record from other tables (Product, Order, OrderDetails) will also be deleted. How can I do this ?
I've tried this This code is in my IdentityModel.cs
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Product>()
.HasRequired(s => s.Store)
.WithMany()
.HasForeignKey(d => d.StoreId)
.WillCascadeOnDelete(false); // also tried with TRUE, didn't work
modelBuilder.Entity<Order>()
.HasRequired(s => s.Store)
.WithMany()
.HasForeignKey(d => d.StoreId)
.WillCascadeOnDelete(false); // also tried with TRUE, didn't work
modelBuilder.Entity<OrderDetail>()
.HasRequired(s => s.Order)
.WithMany()
.HasForeignKey(d => d.OrderId)
.WillCascadeOnDelete(false); // also tried with TRUE, didn't work
}
Controller
[HttpPost]
public ActionResult StoreDelete(int? id, Store store)
{
try
{
if (id == null)
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
store = db.Stores.Find(id);
if (store == null)
{
return HttpNotFound();
}
else
{
db.Stores.Remove(store);
db.SaveChanges();
return RedirectToAction("ManageStores", "Store");
}
}
catch
{
return View();
}
}
View
@using (Html.BeginForm("StoreDelete", "Store", new { id = ViewBag.StoreId }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
<h4 class="text-danger">Are you sure you want to delete this store ?</h4>
<br />
@Html.TextBoxFor(m => m.Name, new { @class = "inputboxes texbboxstyle form-control", @readonly = "readonly" })
<br>
@Html.TextBoxFor(m => m.CreatedOn, new { @class = "inputboxes texbboxstyle form-control", @readonly = "readonly" })
<br>
<input type="submit" class="btn-lg btn-danger" style="border-radius:0px; width:200px;" value="Delete" />
}
