我有以下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代码实现此目的?