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

久未见 提交于 2019-12-23 18:23:22

问题


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

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

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.

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

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.

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.

What am I missing here?


回答1:


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

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.

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.

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



来源:https://stackoverflow.com/questions/4158027/how-do-i-cascade-deletes-into-a-link-table-using-the-ef4-fluent-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!