chuckd
chuckd

Reputation: 14540

Cascade delete using Fluent API

I have two entities. Profile and ProfileImages. After fetching a Profile I want to delete ProfileImages through Profile without it just removing the reference to Profile (setting it to null). How can this be done with fluent API and Cascading Delete? Do I set the HasRequired attribute or the CascadeDelete attribute?

public class Profile 
{
    //other code here for entity
    public virtual ICollection<ProfileImage> ProfileImages { get; set; }
}

public class ProfileImage 
{
    // other code here left out        
    [Index]
    public string ProfileRefId { get; set; }

    [ForeignKey("ProfileRefId")]
    public virtual Profile Profile { get; set; }
}

Upvotes: 4

Views: 5627

Answers (1)

Salah Akbari
Salah Akbari

Reputation: 39956

You can add this to your DB Context:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Profile>()
    .HasOptional(c => c.ProfileImages)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);
}

Read more here:Enabling Cascade Delete

You can configure cascade delete on a relationship by using the WillCascadeOnDelete method. If a foreign key on the dependent entity is not nullable, then Code First sets cascade delete on the relationship. If a foreign key on the dependent entity is nullable, Code First does not set cascade delete on the relationship, and when the principal is deleted the foreign key will be set to null.

Upvotes: 3

Related Questions