级联删除与实体框架和TPT

时间:2015-06-30 19:53:19

标签: c# entity-framework

我有一个Base类,一个Derived类,Derived有一个Items集合。 我想配置EF以删除其父项Derived时删除项目。

以下最小(LinqPad)示例显示了我是如何尝试实现这一点的,但它并没有生成on delete cascade部分,只是常规FK。

我尝试了[必需]属性 - 没有工作。

如何将删除级联选项添加到FK规范中?

[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);
}

这是它生成的DDL:

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]);

0 个答案:

没有答案