简体   繁体   中英

Delete records from multiple tables with foreign key constraint

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" />
}

You can delete multiple records from table but in order like

var Order = db.Orders.where(x=>x.StoreId == store.StoreId) 
var OrderDetail = db.OrderDetails.where(x=>x.OrderId== Order.OrderId) 
var Product = db.Products.where(x=>x.StoreId == store.StoreId)

db.Orders.RemoveRange(Order);
db.OrderDetails.RemoveRange(OrderDetail);
db.Products.RemoveRange(Product);
db.Stores.Remove(store);
db.SaveChanges();

I hope it may works for you

If you want the child entities gone as well, then change the relationship to be cascade on delete and don't forget to update the model

在此输入图像描述

This is also working.

db.OrderDetail.Where(c => c.OrderDetailId == OrderDetailId).ToList()
.ForEach(db.OrderDetail.DeleteOnSubmit);

db.SubmitChanges();`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM