实体框架代码首先对具有多个外键的表进行级联删除

时间:2018-04-27 11:29:21

标签: c# sql entity-framework entity-framework-6

我有以下POCO模型,我试图在客户和学习者之间启用级联删除,但收到错误。

  

引入FOREIGN KEY约束   '客户'表上的'FK_dbo.Customers_dbo.Companies_CompanyId'可以   导致循环或多个级联路径。指定ON DELETE NO ACTION或   ON UPDATE NO ACTION,或修改其他FOREIGN KEY约束。可以   不创造约束。查看以前的错误。

Company.cs

public class Company
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public virtual ICollection<Course> Courses { get; set; }
        public virtual ICollection<Customer> Customers { get; set; }
    }

Customer.cs

public class Customer
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int CompanyId { get; set; }
        public virtual Company Company { get; set; }
        public virtual ICollection<Learner> Learners { get; set; }
    }

Course.cs

 public class Course
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CompanyId { get; set; }
    public virtual Company Company { get; set; }
    public virtual ICollection<Learner> Learners { get; set; }
}

Learner.cs

 public class Learner
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CustomerId { get; set; }
    public virtual Customer Customer { get; set; }
    public int CourseId { get; set; }
    public virtual Course Course { get; set; }
}

映射文件如下:

 public class CompanyMapping : EntityTypeConfiguration<Company>
    {
        public CompanyMapping()
        {

        }
    }

    public class CourseMapping : EntityTypeConfiguration<Course>
    {
        public CourseMapping()
        {
            HasRequired(c => c.Company)
               .WithMany(comp => comp.Courses)
                .HasForeignKey(c => c.CompanyId);
        }
    }

    public class CustomerMapping : EntityTypeConfiguration<Customer>
    {
        public CustomerMapping()
        {
            HasRequired(cust => cust.Company)
               .WithMany(comp => comp.Customers)
               .HasForeignKey(cust => cust.CompanyId);
        }
    }

    public class LearnerMapping : EntityTypeConfiguration<Learner>
    {
        public LearnerMapping()
        {
            HasRequired(l => l.Customer)
                .WithMany(c=>c.Learners)
                .WillCascadeOnDelete(true);


            HasRequired(l => l.Course)
                .WithMany(c=>c.Learners)
                .WillCascadeOnDelete(true);
        }
    }

以下情况完美无缺

  • 当我删除公司的所有客户时,会自动删除课程和学员。
  • 当我删除课程时,学习者也会被删除。
  • 当我删除学习者时,它也很容易被删除。

期望的结果

当我尝试删除客户时。它不会让我这样做是因为它的学习者。我想为客户启用级联删除给学习者。如何首先使用EF代码实现此目的?

0 个答案:

没有答案