Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable cascade delete in TPT (table per type) inheritance in code first?

Tags:

c#

sql

code-first

I'm using EF with Code first and TPT (Table per Type) inheritance. I have the following model:

public partial class AccountHolder
{
    public int AccountHolderId { get; set; }

    public virtual Address Detail { get; set; }  
    public virtual Nominee Nominee { get; set; }   
}

public partial class Nominee
{
    public int NomineeId { get; set; }             
}

public abstract class Address
{
    public int AddressId { get; set; }
    ...
}

public class PersonalDetail : Address
{
    public int PersonalDetailId { get; set; }
    ...
}

Fluent api :

        modelBuilder.Entity<AccountHolder>().HasOptional(p => p.Nominee)
                                            .WithRequired()
                                            .WillCascadeOnDelete();

According to this tutorial here is a polymorphic relationship between AccountHolder and Address. PersonalDetail inherit Address. My issue is whenever i delete any AccountHolder i want that EF will take care of deleting its associated PersonalDetail information from Address and PersonalDetail table but currently this is not happing, can anybody please guid me how i can implement this behavior through fluent API or some other approach ?

Edit:

According to the posted answer when i am using this configuration :

        modelBuilder.Entity<AccountHolder>().HasOptional(p => p.Detail)
                                            .WithRequired()
                                            .WillCascadeOnDelete();

for enabling cascade delete that this is conflicting with existing 1 to 1 association between AccountHolder and Nominee. The exception is :

Conflicting changes detected. This may happen when trying to insert multiple entities with the same key.

like image 526
Gaurav Avatar asked Mar 06 '13 18:03

Gaurav


1 Answers

Check out the WillCascadeOnDelete function when specifying the EntityTypeConfiguration

http://msdn.microsoft.com/en-us/library/gg679348(v=vs.103).aspx

In that example you posted in the question, they have:

modelBuilder.Entity<Customer>()
              .HasOptional(c => c.BillingAddress)
              .WithRequired();

Slap a WillCascadeOnDelete(true) at the end of that (or for whatever Entity you want to have cascade), and that should do it. Something like:

modelBuilder.Entity<AccountHolder>().HasOptional(a => a.Address).WithRequired().WillCascadeOnDelete(true);
like image 81
Stephen Fischer Avatar answered Sep 30 '22 15:09

Stephen Fischer