User, Employer, Candidates and Job, an employer can create multiple jobs and each job can only have one employer, a candidate can apply for many jobs and each job can have multiple applied members.
So the relationship is like this:
I am using entity framework code first approach, at the moment if I delete an employer, it is going to delete all related jobs and the user from database, and if I delete candidate, it is going to delete the user:
modelBuilder.Entity<Employer>()
.HasRequired(e => e.User)
.WithOptional(e => e.Employer).WillCascadeOnDelete();
//member is candidate
modelBuilder.Entity<Member>()
.HasRequired(e => e.User)
.WithOptional(e => e.Member).WillCascadeOnDelete();
modelBuilder.Entity<Employer>()
.HasMany(a => a.Jobs)
.WithRequired(b => b.Employer)
.WillCascadeOnDelete();
Everything works fine except when I specify many to many relationship between candidates and job and update the database using "update-database", it gives me this error:
Introducing FOREIGN KEY constraint 'FK_dbo.MemberJobMap_dbo.Jobs_JobId' on table 'MemberJobMap' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints. Could not create constraint. See previous errors.
Here is how I specified many to many relationship:
modelBuilder.Entity<Member>()
.HasMany(m => m.Jobs)
.WithMany(j => j.Members)
.Map(c =>
{
c.MapLeftKey("Id");
c.MapRightKey("JobId");
c.ToTable("MemberJobMap");
});
and when I add migration:
CreateTable(
"dbo.MemberJobMap",
c => new
{
Id = c.String(nullable: false, maxLength: 128),
JobId = c.Int(nullable: false),
})
.PrimaryKey(t => new { t.Id, t.JobId })
.ForeignKey("dbo.Members", t => t.Id, cascadeDelete: true)
.ForeignKey("dbo.Jobs", t => t.JobId, cascadeDelete: true)
.Index(t => t.Id)
.Index(t => t.JobId);
I tried changing cascadeDelete to false but that gives me error when I delete a candidate that have applied jobs or when I try to delete a job with applied candidates.
How to fix this error? So that:
- When a job is removed, it is going to remove associated candidatejobmap table rows without effecting any other table
- When a candidate is removed, it is going to remove associated candidatejobmap table rows and user table row without effecting any other table
- While keeping all other specified cascade delete action the same