Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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; }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
165 views
Welcome To Ask or Share your Answers For Others

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);
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...