I have two entities in my application and I populated the database with Entity Framework Code First. There are two Employee id in the Task entity; one of them forRequirerEmploye, others for RequestedEmployee
. When make update-database in package manager console I get error like this:
Introducing FOREIGN KEY constraint 'FK_dbo.Tasks_dbo.Employees_DemandingEmployeeID' on table 'Tasks' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
My Task Class:
public int ID { get; set; }
public int DemandingEmployeeID { get; set; }
public int RequestedEmployeeID { get; set; }
[ForeignKey("DemandingEmployeeID")]
[InverseProperty("DemandingTasks")]
public virtual Employee DemandingEmployee { get; set; }
[ForeignKey("RequestedEmployeeID")]
[InverseProperty("RequestedTasks")]
public virtual Employee RequestedEmployee { get; set; }
My Employee Class:
public int ID { get; set; }
public virtual ICollection<Task> DemandingTasks { get; set; }
public virtual ICollection<Task> RequestedTasks { get; set; }
My Context:
modelBuilder.Entity<Task>().HasRequired(m => m.DemandingEmployee).WithMany(m => m.DemandingTasks).HasForeignKey(m => m.DemandingEmployeeID);
modelBuilder.Entity<Task>().HasRequired(m => m.UpdatedEmployee).WithMany(m => m.UpdatedTasks).HasForeignKey(m => m.UpdatedEmployeeID);
The problem is that you have multiple paths of cascade deletes, that could end trying to delete the same row in the database. To understand more about this error, take a look at https://support.microsoft.com/en-us/kb/321843. Follow the steps above to solve the problem.
Change your class:
public int ID { get; set; }
public int DemandingEmployeeID { get; set; }
public int RequestedEmployeeID { get; set; }
public virtual Employee DemandingEmployee { get; set; }
public virtual Employee RequestedEmployee { get; set; }
Change your context:
modelBuilder.Entity<Task>()
.HasRequired(m => m.DemandingEmployee)
.WithMany(m => m.DemandingTasks)
.HasForeignKey(m => m.DemandingEmployeeID)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Task>()
.HasRequired(m => m.RequestedEmployee)
.WithMany(m => m.RequestedTasks)
.HasForeignKey(m => m.RequestedEmployeeId)
.WillCascadeOnDelete(false);
modelBuilder.Entity<Task>()
.HasRequired(m => m.UpdatedEmployee)
.WithMany(m => m.UpdatedTasks)
.HasForeignKey(m => m.UpdatedEmployeeID)
.WillCascadeOnDelete(false);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments