Caribou Caribou - 2 months ago 14
C# Question

Entity Framework 6 - Call a method on removing an entity from the database

I have an entity of a physical file location:

public class MyFile
{
public MyFile() { }
public int FileID { get; set; }
public string URI { get; set; }

DisposeFile()
{
//Remove physicall file here...
}
}


I want the
DisposeFile()
method to be called when I remove
MyFile
entity from the database:

DbContext.MyFile.Remove(someMyFileEntity);
DbContext.SaveChanges(); // Call DisposeFile()


Is there a simple way to do so? Or should I dispose this physical file in other way?

Answer

You can easily achieve what you are looking for by overriding the SaveChanges method of your DbContext class:

public override int SaveChanges()   
{   
    var deletedMyFileEntityList = ChangeTracker.Entries()   
        .Where(f => f.Entity is MyFile && f.State == EntityState.Deleted);   

    foreach (var entity in deletedMyFileEntityList)   
    {
        try {
            entity.DisposeFile();
        }
        catch (Exception ex)
        {
            // Here you can decide what to do if the DisposeFile method fails
        }
    }   

    return base.SaveChanges();   
}