Search code examples
c#databasesql-server-2008entity-frameworkentity-relationship

Removing Parent with one-to-many EntityFramework


I have this class ( Simplified )

public class User {
    public string Username { get; set; }
    public virtual Section Section { get; set; }
}

public class Section {
    public int DepartmentNumber { get; set; }
    public virtual ICollection<User> DepartmentMembers { get; set; }
}

What i try to achive is to delete a section. All users related to this section shoulde get a null value. This dosent work now because REFERENCE constraint "FK_Users_Sections_Section".

What woulde be the correct way to do this? woulde i have to remove all users from this section before deleteing it? Is there a more elegant way to do this? Im using EntityFramework.

My fluent API for this field:

modelBuilder.Entity<User>()
            .HasOptional(u => u.Section)
            .WithMany(s => s.DepartmentMembers)
            .Map(m =>
                m.MapKey("Section")
            )
            .WillCascadeOnDelete(false);

The WillCascadeOnDelete i have tried it by setting to false, removing the line and also adding the line with no arguments.

I guess the solution is quit simple but i cant find any good explaination ( or mabye i dont understand the explainations i have been looking at. )


Solution

  • Although SQL Server has a SET NULL option for cascade deletes, which sets all foreign keys referencing a deleted record to null, Entity Framework does not use it.

    You can either set this option on the constraint yourself in SQL Server, or you can let Entity Framework take care of it by updating loaded entities.

    If you want EntityFramework to do it, you need to make sure the DepartmentMembers collection is loaded, so that all the User objects that will need to be updated are in the context.

    Section s = context.Sections.Include(s => s.DepartmentMembers).First();
    context.Delete(s);
    context.SaveChanges();