I have a Base class, a Derived class and Derived has a collection of Items. I want to configure EF to delete Items when their parent Derived is deleted.
The following minimal (LinqPad) example shows how I'm trying to achieve that, but it doesn't generate the on delete cascade part, just regular FKs.
I tried [Required] attribute - didn't work.
How do I make it add 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 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]);