简体   繁体   English

使用EF的TPT流利语法级联删除子记录

[英]Cascade delete child record using EF's TPT fluent syntax

I'm trying to get a basic example of TPT working. 我正在尝试获得TPT工作的基本示例。 Most references discuss TPT in general, and how it works, but don't go into the actual fluent mapping details. 大多数参考文献一般都讨论了TPT及其工作原理,但没有涉及实际的流畅映射细节。 This is what I have so far: 这是我到目前为止的内容:

public abstract class Parent {
  public Parent() { }
  public int Id { get; set; }
  // other properties...
}

public class Child : Parent {
  public Child() : base() { }
  // other properties...
}

public class MyContext : DbContext {
  protected override void OnModelCreating(DbModelBuilder modelBuilder) {

    var p = modelBuilder.Entity<Parent>();
    p.ToTable("Parent");
    p.HasKey(m => m.Id);
    p.Property(m => m.Id).HasColumnName("Id").IsRequired().HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

    var c = modelBuilder.Entity<Child>();
    c.ToTable("Child");
    //c.HasKey(m => m.Id);                                     // needed?
    //c.Property(m => m.Id).HasColumnName("Id").IsRequired();  // needed?

  }
}

Is this all that I need to do? 这就是我需要做的吗? Is there a reference example for this specific case somewhere? 在某处是否有针对此特定案例的参考示例?

UPDATE: 更新:
Thanks to the comments, I've discovered that this is correct, and that things are mapped by convention. 多亏了这些评论,我发现这是正确的,并且按照约定映射了事物。

What I've discovered though is that a child record is not cascade deleted automatically when a parent record is deleted. 但是我发现,删除父记录时,不会自动删除子记录。 I can change this via script, but I want to use an EF approach. 我可以通过脚本更改它,但是我想使用EF方法。 How do I configure the child to do that? 我该如何配置孩子来做到这一点?

From reviewing other questions going way way back, looks like a bug/missing feature. 从回顾过去的其他问题来看,它看起来像一个错误/缺失功能。 And there's no clear solution... which I've found. 而且还没有明确的解决方案...我已经找到了。

So unless someone has a better idea, I'll need to create an empty migration, and add the necessary sql statements to force the cascade delete: 因此,除非有人有更好的主意,否则我将需要创建一个空迁移,并添加必要的sql语句以强制级联删除:

AddForeignKey("dbo.Child", "Id", "dbo.Parent", "Id", true);    // <- true is the trick

...which generates: ...会产生:

ALTER TABLE [Child] ADD CONSTRAINT [FK_dbo.Child_dbo.Parent_Id]
FOREIGN KEY ([Id]) REFERENCES [Parent]([Id]) ON DELETE CASCADE ON UPDATE NO ACTION;

Notice the ON DELETE CASCADE . 注意ON DELETE CASCADE

Please tell me if there is a better way? 请告诉我是否有更好的方法? (ie one that doesn't require me fiddling with migrations and/or SQL.) (即不需要我精通迁移和/或SQL的软件。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM