'The association between entities (with the key value, CreatedById:200) has been severed - Error
While I try to delete a ProjectParticipant object from a Project object and call context.SaveChangesAsync(), I get this error:
ERROR: The association between entities ‘employee’ and ‘project’ with the key value ,CreatedById:200 has been severed but the relationship is either marked as ‘required’ or is implicitly required because the foreign key is not billable of the dependent/child entity should be deleted when a required relationship is severed, then setup the relationship to use cascade deletes.
Could someone help me fix this?
Project.cs
public class Project
{
public Project()
{
ProjectParticipants = new HashSet<ProjectParticipant>();
}
public int Id { get; set; }
public int CreatedById { get; set; }
public Employee CreatedBy { get; set; }
public virtual ICollection<ProjectParticipant> ProjectParticipants { get; set; }
}
}
Employee.cs
public class Employee
{
public Employee()
{
Projects = new HashSet<Project>();
ProjectParticipants = new HashSet<ProjectParticipant>();
}
public int Id { get; set; }
public virtual ICollection<Project> Projects { get; set; }
public virtual ICollection<ProjectParticipant> ProjectParticipants { get; set; }
}
ProjectParticipant.cs
public class ProjectParticipant
{
public ProjectParticipant()
{
}
public int Id { get; set; }
public int ProjectId { get; set; }
public virtual Project Project { get; set; }
public int EmployeeId { get; set; }
public virtual Employee Employee { get; set; }
}
ProjectDBContext.cs
public class ProjectDBContext:DBContext
{
public override OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Project>(entity => {
...
entity.HasOne(d => d.CreatedBy)
.WithMany(a => a.Projects)
.HasForeignKey(d => d.CreatedById)
.OnDelete(DeleteBehavior.ClientSetNull)
.HasConstraintName("FK_Project_Employee_CreatedBy");
...
});
modelBuilder.Entity<ProjectParticipant>(entity => {
...
entity.HasOne(d => d.Employee)
.WithMany(a => a.ProjectParticipants)
.HasForeignKey(d => d.EmployeeId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_ProjectParticipants_Employee");
entity.HasOne(d => d.Project)
.WithMany(a => a.ProjectParticipants)
.HasForeignKey(d => d.ProjectId)
.OnDelete(DeleteBehavior.Cascade)
.HasConstraintName("FK_ProjectParticipants_Project");
...
});
modelBuilder.Entity<Employee>(entity => {
...
});
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
