使用EF4流畅的API将删除链接级联到链接表中? [英] How do I cascade deletes into a link table using the EF4 fluent API?

查看:124
本文介绍了使用EF4流畅的API将删除链接级联到链接表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在现有的(MSSQL 2008 R2)数据库中有两个与链接表相关的表。

I have two tables in an existing (MSSQL 2008 R2) database that are related by a link table.

这两个表是计划和提示 。链接表是PlanTipLinks。

The two tables are "Plan" and "Tips". The link table is "PlanTipLinks".

计划可以有许多提示,并且提示可以与多个计划相关联(即,它是多对多关系)。在应用程序中,我只关心Plan.Tips关系。我不需要Tip.Plans反向关系。

Plans can have many tips, and tips can be associated with multiple plans (i.e. it's a many-to-many relationship). In the application, I only care about the "Plan.Tips" relationship. I don't need the Tip.Plans inverse relationship.

链接表中的外键引用不能为空。

The foreign key references in the link table cannot be null.

我使用以下流畅的API代码来映射此关系:

I'm using the following fluent API code to map this relationship:

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

在表中创建正确的条目。问题是,当我删除一个计划时,我在PlanTipLinks表中得到一个外键异常。

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表中,当计划被删除,但我不知道如何做到这一点。我似乎无法使用HasMany / WithMany方法调用WillCascadeOnDelete方法。

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. I don't seem to be able to call the WillCascadeOnDelete method using the HasMany/WithMany methods.

我在这里缺少什么?

推荐答案

从EF CTP4开始,没有办法直接在Fluent API中启用多对多关联的级联删除。

As of EF CTP4, there is no way to directly turn on cascade deletes on Many to Many associations by Fluent API.

这就是说,如果你的意图是确保你可以删除原则(例如,计划记录),而不用担心依赖记录链接表(即 PlanTipLinks )然后您不需要打开数据库上的级联,因为EF Code First将在客户端处理多个到多个关联的级联删除。

That said, if your intention is to make sure that you can delete the principle (e.g. a Plan record) without having to worry about the dependent record in the link table (i.e. 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 表中,之后它将发送另一个删除语句来删除计划记录。

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.

有关更多信息,请查看以下帖子:


EF CTP4级联删除多对多关系

For more info, please take a look at the following post:
EF CTP4 cascade delete on many to many relationship

这篇关于使用EF4流畅的API将删除链接级联到链接表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆