I have 2 entities linked by a one-to-many relationship as follows (I used code first):
public class Computer
{
[Key]
public int ComputerId { get; set; }
[Required]
public int ComputerIdInventory { get; set; }
[DataType(DataType.Date)]
public DateTime? AcquisitionDate { get; set; }
[DataType(DataType.Date)]
public DateTime? LastUpdate { get; set; }
public string Comment { get; set; }
//Foreign keys
public int? ComputerModelId { get; set; }
public int? EmployeeId { get; set; }
//Navigation properties
public virtual ICollection<Screen> Screens { get; set; }
}
public class Screen
{
[Key]
public int ScreenId { get; set; }
[Required]
public int ScreenIdInventory { get; set; }
public string Comment { get; set; }
//Foreign keys
public int? ComputerId { get; set; }
//Navigation properties
public virtual Computer Computer { get; set; }
}
When I delete a computer that is linked to one or many screens, I have the following error:
[SqlException (0x80131904): The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Screen_dbo.Computer_ComputerId". The conflict occurred in database "CPInventory", table "dbo.Screen", column 'ComputerId'.
I have read many posts, and I tried 2 things that seemed to have worked for others. I changed the "OnModelCreating" method and added :
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
And I tried this too:
modelBuilder.Entity<Computer>()
.HasMany<Screen>(c => c.Screens)
.WithOptional(s => s.Computer)
.WillCascadeOnDelete(false);
But none of the solutions worked... Am I doing something wrong ? I also update the database but nothing has changed. Do I have to completely drop my database and recreate it in order for those changes to be taken into account?
Thank a lot !
Edit: Here is the delete code
public ActionResult DeleteConfirmed(int id)
{
Computer computer = db.Computers.Find(id);
db.Computers.Remove(computer);
db.SaveChanges();
return RedirectToAction("Index");
}