3

I've got a simple model that looks like this:

public class ImageFile
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public ImageMeta Meta { get; set; }
    public string FileName { get; set; }
    public DateTime DateUploaded { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
}

Is there any way I can add some kind of "OnDelete" event hook so that whenever a model is deleted via db.Images.Remove(imageFile); or whatever other means, I can delete the associated file?

mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • Are you looking to also detect deletions that are cascaded? That is my trouble. – Derrick Oct 24 '13 at 15:13
  • @Derrick: Yeah, that would be helpful. I haven't touched this project in awhile, but ideally there would be a hook that would always run on deletion so it never got out of sync. – mpen Oct 24 '13 at 15:28

1 Answers1

3

You can override the SaveChanges method of your context to hook up to delete entities.

public class GalleryContext : DbContext
{
     public override int SaveChanges()
     {
          var deletedImages = ChangeTracker.Entries()
              .Where(e => e.State == EntityState.Deleted && e.Entity is ImageFile)
              .Select(e => e.Entity).Cast<ImageFile>();

          foreach(var image in deletedImages)
          {
              // delete file here or call a method on image
          }

          return base.SaveChanges();
     }
}
Eranga
  • 32,181
  • 5
  • 97
  • 96