使用外键约束从多个表中删除记录

时间:2016-02-10 09:34:01

标签: c# entity-framework

我正在使用Asp.Net MVC并构建电子商务应用程序。

我的数据库中有4个表

ProductProductId(PK), Name, Price, StoreId(FK)

StoreStoreId(PK), Name, CreatedOn

OrderOrderId(PK), StoreId(FK), OrderDate, OrderTotal

OrderDetailOrderDetailId(PK), OrderId(FK), Quantity, UnitPrice, Weight

当我尝试删除单个产品时,它没有给出任何错误并删除了产品,如果我删除了Order记录它给出了OrderDetails外键的错误,我知道我必须删除OrderDetail记录首先是订单记录。

我的情况是,Store有多个产品,每个商店都有订单,然后订购详细信息。

现在,我不想每次删除单个记录,因为它需要很多时间。我想删除一个STORE,其他表(Product,Order,OrderDetails)中的所有记录也将被删除。我怎么能这样做?

我试过这个这段代码在我的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
    }

控制器

[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();
        }
    }

查看

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

3 个答案:

答案 0 :(得分:12)

您可以按顺序删除表中的多条记录 喜欢

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();

我希望它可能适合你

答案 1 :(得分:2)

如果您希望子实体也消失,那么在删除时将关系更改为级联,不要忘记更新模型

enter image description here

答案 2 :(得分:0)

这也可以。

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

db.SubmitChanges();`