CodeFirst 级联删除问题

codefirst涉及到级联删除时可能会报下面的错误:

table 'TableName' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.

这是由于同一张表中使用了同一个外键表,且codefirst自动为它们创建了级联删除约束。

此时可以在OnModelCreating方法中设置不创建级联删除约束(实际开发中需要我手动实现级联删除):

protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Appointment>().HasRequired(a => a.Sponsor).WithMany(u => u.SpoAppointments).WillCascadeOnDelete(false);
            modelBuilder.Entity<Appointment>().HasRequired(a => a.Recipient).WithMany(u => u.RecAppointments).WillCascadeOnDelete(false);
        }

参考链接:http://www.cnblogs.com/Gyoung/archive/2013/01/22/2871919.html

你可能感兴趣的:(CodeFirst 级联删除问题)