One To Many Relationship - Cascading Delete
I'm using EF 4.1 where I'm trying to map my POCO to my existing database. This is working fine until I try to delete an item that the other item has a dependency to. I want to enable cascading deletes, so that when my first item is deleted all dependencies would also be deleted (I believe this is called cascading delete).
I tried to enable this in the OnModelCreating:
modelBuilder.Entity<Component>()
.HasMany(c => c.Specifications)
.WithRequired(s => s.Component)
.Map(m => m.MapKey("ComponentId"))
.WillCascadeOnDelete(true);
However, I still get the The DELETE statement conflicted with the REFERENCE constraint
exception.
The database is quite simple:
Component:
ComponentId (PK) Description
Specification:
SpecificationID (PK) Description ComponentID (FK)
I've crea开发者_Go百科ted the two following classes to match this setup:
public class Specification
{
[Key]
[Required]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Description { get; set; }
public virtual Component Component { get; set; }
}
and
public class Component
{
[Key]
[Required]
public int Id { get; set; }
[MaxLength(50)]
[Required]
public string Description { get; set; }
public virtual ICollection<Specification> Specifications { get; set; }
}
Cascading delete in your model requires cascading delete in your DB. If you let the EF recreate the DB for you, it will set this up automatically. If you cannot let the EF do this, then you must either:
- Add cascading delete to the FK manually, or
- Remove the cascade from the model.
精彩评论