Code first TPT and cascade on delete

Viewed 1718

I'm using EF4.1 with Code first and TPT (Table per Type) inheritance. I have a structure like this

public class Customer 
{
    public virtual ICollection<Product> Products {get; set;}
}

public class Product
{
   [Required]
   public int Id { get; set; }

   [Required]
   public virtual Customer {get; set;}

   public decimal Price { get; set; }
}

public class SpecializedProduct : Product
{
   public string SpecialAttribute { get; set; }
}

when i delete a customer i want all the products associated with that customer to be deleted. I can specify a WillCascadeOnDelete(true) between the Customer and the Product:

modelBuilder.Entity<Customer>().HasMany(e => e.Products).WithRequired(p => p.Customer).WillCascadeOnDelete(true);

but since there's a foreighn key relationship between SpecializedProduct and Product i get an Exception when I try to delete the Customer:

The DELETE statement conflicted with the REFERENCE constraint "SpecializedProduct _TypeConstraint_From_Product_To_SpecializedProduct". The conflict occurred in database "Test", table "dbo.SpecializedProduct", column 'Id'. The statement has been terminated.

If i manually set a on delete cascade on the SpecializedProduct _TypeConstraint_From_Product_To_SpecializedProduct constraint it works, but i would like to be able to specify this using the modelbuilder or some other way in code. Is this possible?

Thanks in advance!

Best Regards

Simon

1 Answers
Related