EF Code First Fluent API - Cascade Delete

2019-05-30 12:59发布

问题:

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?

回答1:

Use WillCascadeOnDelete

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