实体框架6阻止删除

时间:2015-11-06 03:55:54

标签: c# entity-framework many-to-many

如何让EF不允许删除相关实体?例如:

public class Enrollment 
{
    public int EnrollmentId { get; set; }
    public virtual ICollection<Course> courses { get; set; }
}

public class Course 
{
    public int CourseId { get; set; }
    public string Name { get; set; }
}

当我创建课程A和B,然后我创建一个注册并将这些课程添加到它时,我需要它不允许我删除课程A或B.当我通过我的MVC控制器运行它时没有问题:

Course course = db.Courses.Find(id);
db.Courses.Remove(course);
db.SaveChanges();

我甚至不确定要搜索的内容。我认为它强制执行或启用多对多参考约束?但我似乎找不到任何东西。我不应该期望它会自动制定约束吗?我想我总是可以将以下行添加到删除控制器:

if(db.Enrollments.Any(e => e.Courses.Any(c => c.CourseId == id)))
{ //error }

此外,尝试以下流利的API并不起作用(在许多变体中):

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Enrollment>()
               .HasMany<Course>(e => e.Courses)
               .WithRequired()
               .WillCascadeOnDelete(false);
        modelBuilder.Entity<Course>()
               .HasMany(e => e.Enrollments);
        base.OnModelCreating(modelBuilder);
    }

1 个答案:

答案 0 :(得分:0)

  

如何让EF不允许删除相关实体?

您想要阻止删除正在使用的内容,对吗?课程和入学是多对多的关系吗?默认情况下,许多人不会在删除时级联。尝试改变这一点。

public class Enrollment 
{
    public int EnrollmentId { get; set; }
    public virtual ICollection<Course> Courses { get; set; }
}

public class Course 
{
    public int CourseId { get; set; }
    public string Name { get; set; }
    public virtual ICollection<Enrollment> Enrollments { get; set; }
}

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //Need this to remove the cascade convention.
    modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
}