Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EntityFramework Migration cascadeDelete parameter

I'm using EF 4.3 migration feature to create database migration scripts. When I run Add-Migration command the generated script is created as so:

        CreateTable(
            "dbo.Recipients",
            c => new
                {
                    RecipientID = c.String(nullable: false, maxLength: 128),
                    SurveyRoundID = c.String(nullable: false, maxLength: 128),
                    LastUpdatedAt = c.DateTime(),
                })
            .PrimaryKey(t => t.RecipientID)
            .ForeignKey("dbo.Employees", t => t.EmployeeID, cascadeDelete: true)
            .ForeignKey("dbo.SurveyRounds", t => t.SurveyRoundID, cascadeDelete: true)
            .Index(t => t.EmployeeID)
            .Index(t => t.SurveyRoundID);

The problem I have is that the scafolding migration choose cascadeDelete to be true even though the entity Recipient is not the master of the relation.

For now I'm manually changing the cascadeDelete parameter to false but I would like to know why it choosing true by default.

Thank you, Ido.

like image 244
Ido Ran Avatar asked Aug 14 '12 10:08

Ido Ran


2 Answers

Thanks for the answer, it helped me as I was noticing and sometimes having errors when trying to update database as several of my classes have multiple relations making cascade delete not ideal.

Please see below for removing cascade delete default setting:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
}

This go inside Context class.

like image 134
danfer Avatar answered Oct 19 '22 16:10

danfer


It works as expected. It is not principal entity in the relation and because of that it defines foreign key constraint and this constraint has cascade delete option. Setting cascade delete to true (default in EF code first unless you remove the convention or change it in fluent mapping) says that if Employee record is deleted the cascade delete will trigger deletion of Recipient (the same apply on SurveyRounds).

This model is really not ideal for cascade delete because the entity is dependent in multiple relations. You should remove cascade delete directly in the entity mapping.

like image 37
Ladislav Mrnka Avatar answered Oct 19 '22 15:10

Ladislav Mrnka