Pergunta

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?

Foi útil?

Solução

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

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top