Cascade Delete Rule in EF 4.1 Code First when using Shared Primary Key Association

你离开我真会死。 提交于 2019-11-28 10:16:34

The following fluent API code perfectly switch on the cascade delete on the database:

public class Student
{   
    public virtual int StudentId { get; set; }
    public virtual Anamnesis Anamnesis { get; set; }
}

public class Anamnesis
{        
    public int AnamnesisId { get; set; }
    public virtual Student Student { get; set; }
}

public class Context : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Anamnesis> Anamnesises { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Student>()
                    .HasRequired(s => s.Anamnesis)
                    .WithRequiredPrincipal(a => a.Student)
                    .WillCascadeOnDelete();
    }
}

Also, you can use [Required] Attribute, and it will automatically set the delete rule to "CASCADE" mode in related relationship. (and also set "Allow Null" property of that entity to "false" in DB)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!