级联删除MySQL和ASP.NET MVC4

时间:2014-12-07 15:15:49

标签: mysql asp.net-mvc cascade cascading-deletes

我用mysql数据库创建了简单的asp.net(MVC4)网页。我有两个表(人员和订单),其中表格订单有FORIGN Key Persons_ID。我想创建删除功能,所以,当我从人员表中删除人员时,它也会删除此人的订单表中的所有订单。

为了创建模型,我使用了ADO.NET,并为每个表创建了这两个模型:

persons.cs     使用System.ComponentModel.DataAnnotations;

namespace MvcMySQLTest1.Models
{
    using System;
    using System.Collections.Generic;

    public partial class person
    {
        public person()
        {
            this.orders = new HashSet<order>();
        }

        public int ID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Adress { get; set; }
        public string City { get; set; }

        public virtual ICollection<order> orders { get; set; }
    }
}

orders.cs

using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;

namespace MvcMySQLTest1.Models
{
    using System;
    using System.Collections.Generic;

    public partial class order
    {
        public int O_Id { get; set; }
        public int OrderNo { get; set; }
        public Nullable<int> Persons_Id { get; set; }

        public virtual person person { get; set; }

    }
}

我还创建了MainModel - 就像上面两个模型的I容器一样:

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace MvcMySQLTest1.Models
{
    public class MainModel 
    {

        public person Persons { get; set; }

        public order Orders { get; set; }

    }
}

现在对于Cascade删除我试试这个 - 所以当我删除Person时,它也会在订单表中删除此Person的所有订单,但这似乎不能正常工作

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;

namespace MvcMySQLTest1.Models
{
    public class MainModel : DbContext //added
    {

        public person Persons { get; set; }

        public order Orders { get; set; }

        //added  
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {

        modelBuilder.Entity<orders>()
          .HasOptional(a => a.persons)
          .WithOptionalDependent()
          .WillCascadeOnDelete(true);

        base.OnModelCreating(modelBuilder);
        }
    }
}

1 个答案:

答案 0 :(得分:1)

可能你可以尝试这样的事情

modelBuilder.Entity<order>() 
    .HasRequired(a => a.person) 
    .WithMany(t => t.order) 
    .HasForeignKey(d => d.Persons_Id) 
    .WillCascadeOnDelete(true);

或尝试在此处阅读更多内容MSDN Cascade Delete。可以从那里得到帮助