Search code examples
entity-frameworkasp.net-mvc-5entity-relationshipasp.net-identity-2

EF Code First Fluent API - Cascade Delete


I have two models:

public class User
{
   .....
   public virtual UserProfile UserProfile { get; set;}
}


public class UserProfile
{
   .....
   public virtual User User { get; set;}
}

The User is the master table and the relation is one to one. One user has only one UserProfile.

How can I define the relationship between User and UserProfile using EF CodeFirst Fluent API in such a way that when I delete one user from User table the user profile from Userprofile is also deleted?


Solution

  • Use WillCascadeOnDelete

    modelBuilder.Entity<UserProfile>()
        .HasKey(c => c.Id)
        .HasRequired(c => c.User)
        .WithRequiredDependent(c => c.UserProfile)
        .WillCascadeOnDelete(true);