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

前端 未结 2 714
误落风尘
误落风尘 2020-12-10 07:17

I implemented a bidirectional 1:1 relationship based on this answer:

Primary /Foreign Key in Entity Framework

I define the bidirectional relation this way:

相关标签:
2条回答
  • 2020-12-10 07:31

    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)

    0 讨论(0)
  • 2020-12-10 07:48

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

    enter image description here

    0 讨论(0)
提交回复
热议问题