EF Code First级联删除不起作用

时间:2015-09-12 16:56:01

标签: entity-framework

我有4张桌子:

用户表

public enum SEX { Male, Female }

public abstract class User
{

    public int UserID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Phone { get; set; }
    public SEX Sex { get; set; }
}

医生表继承自用户

[Table("Doctor")]
public class Doctor : User
{
    public string Department { get; set; }
    public string Occupation { get; set; }
    public string CabinetNumber { get; set; }

    public virtual List<Treat> Treats { get; set; }
}

患者表继承自用户

[Table("Patient")]
public class Patient : User
{
    public int InsuranceNumber { get; set; }
    public int CardNumber { get; set; }

    public virtual List<Treat> Treats { get; set; }
}

public class Treat
{
    public int TreatId { get; set; }

    public int DoctorUserId { get; set; }
    public int PatientUserId { get; set; }

    public virtual Doctor Doctor { get; set; }
    public virtual Patient Patient { get; set; }
}

public class HospitalContext: DbContext
    {
        public HospitalContext() : base("DBConnectionString") {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<HospitalContext>());
        }
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Treat>()
                .HasRequired(x => x.Doctor)
                .WithMany( x => x.Treats)
                .HasForeignKey( x => x.DoctorUserId)
                .WillCascadeOnDelete(true);

            modelBuilder.Entity<Treat>()
                .HasRequired(x => x.Patient)
                .WithMany( x => x.Treats)
                .HasForeignKey( x => x.PatientUserId)
                .WillCascadeOnDelete(true);

            base.OnModelCreating(modelBuilder);
        }
        public DbSet<User> Users { get; set; }
        public DbSet<Treat> Treats { get; set; }
    }

我在这里找到了很多答案,但他们中没有人工作。我花了几个小时试图让它工作。我知道当存在一对多关系时,实体框架必须启用级联删除,但它不是

1 个答案:

答案 0 :(得分:2)

实体框架不会对TPT(每种类型的表)继承应用级联删除。您可以使用Code Fist迁移解决此问题:

CreateTable(
    "dbo.Treats",
    c => new
    {
        TreatId = c.Int(nullable: false, identity: true),
        DoctorUserId = c.Int(nullable: false),
        PatientUserId = c.Int(nullable: false),
    })
    .PrimaryKey(t => t.TreatId)
    .ForeignKey("dbo.Doctor", t => t.DoctorUserId, cascadeDelete: true)
    .ForeignKey("dbo.Patient", t => t.PatientUserId, cascadeDelete: true)
    .Index(t => t.DoctorUserId)
    .Index(t => t.PatientUserId);

重要的部分是cascadeDelete: true。您必须在生成迁移代码后手动添加它。之后,您将在数据库中删除级联:

FOREIGN KEY ([DoctorUserId]) REFERENCES [dbo].[Doctor] ([UserID]) ON DELETE CASCADE,
FOREIGN KEY ([PatientUserId]) REFERENCES [dbo].[Patient] ([UserID]) ON DELETE CASCADE