Cascade Removal Using the Fluent API

I have two objects. Profileand ProfileImages. After removing ProfileI want to remove ProfileImagesthrough Profilewithout removing references to Profile(set it to null). How can this be done using the free API and Cascading Delete? Set attribute HasRequiredor attribute CascadeDelete?

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; }
}
+4
source share
1 answer

You can add this to your DB Context:

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

More details here: Enabling Cascade Delete

, WillCascadeOnDelete. , Code First . , First , , null.

+3

Source: https://habr.com/ru/post/1618249/


All Articles