Sisyphus
Sisyphus

Reputation: 910

Cascaded delete is not working in EF 6 Code First

I have the following entities

public class Division
{
    public int Id { get; set; }
    public SubDivision SubDivision { get; set; }
}

public class SubDivision
{
    public int Id { get; set; }
}

Then fluent API

            modelBuilder.Entity<Division>()
                        .HasOptional(x => x.SubDivision)
                        .WithOptionalDependent()
                        .WillCascadeOnDelete(true);

Then I try to delete a Division and I am expecting its SubDivisions to be deleted by the don't

Division div = c.Divisions.Include(x => x.SubDivision).First();
c.Divisions.Remove(div);
c.SaveChanges();

Any idea what is the problem?

Upvotes: 1

Views: 907

Answers (1)

Ivan Stoev
Ivan Stoev

Reputation: 205629

Cascade delete works always from principal (the entity being referenced) to dependent (the entity referencing it), i.e. deleting the principal automatically deletes the dependent(s).

In one-to-many relationship the principal is always the one side and dependent - the many side.

In one-to-one relationship the required end is always the principal and the optional end - dependent. However if both ends are required or both ends are optional (as yours), the principal and dependent are determined by the configuration. In your case, the .WithOptionalDependent() line is telling EF that the entity being configured (Division) is the dependent, hence Division will have a FK to SubDivision and deleting the SubDivision will also delete the Division.

If the intent was different (as it seems by the question), simply replace

.WithOptionalDependent()

with

.WithOptionalPrincipal()

Upvotes: 1

Related Questions