Cascading deletes using Entity Framework and TPT

I have a base class, the Derived class and Derived has a set of elements. I want to configure EF to remove items when their parent Derived is deleted.

The following minimal example (LinqPad) shows how I am trying to achieve this, but it does not generate the cascading part of delete, but only regular FKs.

I tried the [Required] attribute - it did not work.

How can I add the delete cascade option to the FK specification?

[System.ComponentModel.DataAnnotations.Schema.Table("Bases")]
public class Base
{
    public int Id {get;set;}
    public string Name {get; set;}
}
[System.ComponentModel.DataAnnotations.Schema.Table("Derived")]
public class Derived : Base
{
    public virtual ICollection<Item> Items {get;set;}

    public Derived()
    {
        Items = new HashSet<Item>();
    }
}

public class Item 
{
    public int Id {get;set;}

    public int ParentId {get;set;}
    public Derived Parent {get;set;}
}

public class TestDbContext : System.Data.Entity.DbContext
{
    public System.Data.Entity.DbSet<Base> Bases { get; set; }
    public System.Data.Entity.DbSet<Derived> Derived { get; set; }
    public System.Data.Entity.DbSet<Item> Items { get; set; }

    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        System.Data.Entity.Database.SetInitializer<TestDbContext>(null);                    
        modelBuilder.Entity<Item>().HasRequired(x=>x.Parent).WithMany(x=>x.Items).HasForeignKey(x=>x.ParentId).WillCascadeOnDelete(true);
    }
}

void Main()
{
    var ctx = new TestDbContext();
    var ddl = (ctx as   System.Data.Entity.Infrastructure.IObjectContextAdapter).ObjectContext.CreateDatabaseScript();
    Console.WriteLine(ddl);
}

This is the DDL that it generates:

create table [dbo].[Bases] (
    [Id] [int] not null identity,
    [Name] [nvarchar](max) null,
    primary key ([Id])
);
create table [dbo].[Derived] (
    [Id] [int] not null,
    primary key ([Id])
);
create table [dbo].[Items] (
    [Id] [int] not null identity,
    [ParentId] [int] not null,
    primary key ([Id])
);
alter table [dbo].[Derived] add constraint [Derived_TypeConstraint_From_Base_To_Derived] foreign key ([Id]) references [dbo].[Bases]([Id]);
alter table [dbo].[Items] add constraint [Item_Parent] foreign key ([ParentId]) references [dbo].[Derived]([Id]);
+4
source share

All Articles