【问题标题】:Cascade Delete for MySQL and ASP.NET MVC4MySQL 和 ASP.NET MVC4 的级联删除
【发布时间】:2014-12-07 15:15:49
【问题描述】:

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

为了创建模型,我使用了 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; }

    }
}

现在对于级联删除我已经尝试过 - 所以当我删除人员时,它也会删除订单表中此人员的所有订单,但这似乎不起作用

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

【问题讨论】:

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


    【解决方案1】:

    也许你可以试试这样的东西

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

    或尝试在此处阅读更多信息 MSDN Cascade Delete。可能有什么可以从那里得到帮助

    【讨论】:

    • tnx 回复,我会尽快尝试。但我给你投票。
    猜你喜欢
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 2016-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    相关资源
    最近更新 更多