Terrance00
Terrance00

Reputation: 1678

Call a Function When Removing an Entity - Delete File

Problem Statement:

I've got the models set up with a one to many as follows:

public class ArticleHeading
{
    [Key]
    public int ArticleHeadingID

    public string ArticleHeadingName {get;set;}

    public virtual ICollection<Article> Articles {get;set;}

}

public class Article
{
    [Key]
    public int ArticleID {get;set;}

    [Required]
    public string ArticleContent {get;set;}

    [Required]
    [ForeignKey("ArticleHeadingID")]
    public virtual ArticleHeading Heading {get;set;}
    
    [Required]
    public int ArticleHeadingID {get;set;}

    [Required]
    public string ArticleImagePath {get;set;}
}

Note: Some data members omitted because it is not relevant.

What I want to achieve is that when I delete an

ArticleHeading
I want to also remove the images with this path:
ArticleImagePath

So the following code:

_context.ArticleHeadings.Remove(someArticleHeading);

Deletes all the Articles connected to it successfully, but I need to delete the images located at the paths inside the articles.

I could manually iterate through the articles easily, but I want to know if it is possible to override or extend that remove method so that I don't have to do it multiple times.

Upvotes: 0

Views: 213

Answers (1)

Joel Waymack
Joel Waymack

Reputation: 136

Normally you'd want to create a layered architecture and take care of those concerns at the service or repository layer. The best way to do this without making those layers is to override the SaveChanges method in your Context class. Something like the following should get you going in the right direction.

public override int SaveChanges()
{
    var deletedArticleHeadings = ChangeTracker.Entries<ArticleHeading>().Where(x => x.State == EntityState.Deleted).ToList();

    foreach (var headingEntry in deletedArticleHeadings)
    {
        var heading = headingEntry.Entity;

        // Delete things.
    }

    return base.SaveChanges();
}

Upvotes: 1

Related Questions