简体   繁体   English

如何使用EF4 fluent API将删除级联到链接表中?

[英]How do I cascade deletes into a link table using the EF4 fluent API?

I have two tables in an existing (MSSQL 2008 R2) database that are related by a link table. 我在现有(MSSQL 2008 R2)数据库中有两个表,它们通过链接表相关联。

The two tables are "Plan" and "Tips". 这两个表是“计划”和“提示”。 The link table is "PlanTipLinks". 链接表是“PlanTipLinks”。

Plans can have many tips, and tips can be associated with multiple plans (ie it's a many-to-many relationship). 计划可以提供许多提示,并且提示可以与多个计划相关联(即,它是多对多关系)。 In the application, I only care about the "Plan.Tips" relationship. 在应用程序中,我只关心“Plan.Tips”关系。 I don't need the Tip.Plans inverse relationship. 我不需要Tip.Plans反向关系。

The foreign key references in the link table cannot be null. 链接表中的外键引用不能为null。

I'm using the following fluent API code to map this relationship: 我正在使用以下流畅的API代码来映射此关系:

modelBuilder.Entity<Plan>()
    .HasMany(p => p.Tips)
    .WithMany()
    .Map("PlanTipLinks", (p, t) =>
        new
        {
            PlanId = p.Id,
            TipId = t.Id
        });

This create the correct entries in the table. 这将在表中创建正确的条目。 Problem is that, when I delete a plan, I get a foreign key exception on the PlanTipLinks table. 问题是,当我删除计划时,我在PlanTipLinks表上获得了外键异常。

Presumably I need to tell it to cascade into the PlanTipLinks table when a plan is deleted, but I'm not sure how to do that. 据推测,当删除计划时,我需要告诉它级联到PlanTipLinks表中,但我不知道该怎么做。 I don't seem to be able to call the WillCascadeOnDelete method using the HasMany/WithMany methods. 我似乎无法使用HasMany / WithMany方法调用WillCascadeOnDelete方法。

What am I missing here? 我在这里错过了什么?

As of EF CTP4, there is no way to directly turn on cascade deletes on Many to Many associations by Fluent API. 从EF CTP4开始,Fluent API无法直接打开多对多关联的级联删除。

That said, if your intention is to make sure that you can delete the principle (eg a Plan record) without having to worry about the dependent record in the link table (ie PlanTipLinks ) then you don't need to turn on cascades on the database since EF Code First will take care of the cascade deletes on the client side when it comes to Many to Many associations. 也就是说,如果您的目的是确保您可以删除原则(例如计划记录)而不必担心链接表中的依赖记录(即PlanTipLinks ),那么您不需要打开级联数据库,因为EF Code First将在多对多关联中处理客户端的级联删除。

For example, when you delete a Plan object, code first is smart enough to first send a delete statement to get rid of the dependent record in the PlanTipLinks table and after that it will send another delete statement to delete the Plan record. 例如,当您删除Plan对象时,代码首先足够聪明,首先发送一个删除语句以除去PlanTipLinks表中的依赖记录,之后它将发送另一个删除语句来删除Plan记录。

For more info, please take a look at the following post: 有关详细信息,请查看以下帖子:
EF CTP4 cascade delete on many to many relationship EF CTP4级联删除多对多关系

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

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