Daveo
Daveo

Reputation: 19882

OnDelete also delete file

Using EF4.1 is there a event of function I can override on my POCO that will be called when it is deleted? I save images on the file system with the DB containing a reference to the file. When I delete from the DB I also want to delete the matching file.

Upvotes: 3

Views: 125

Answers (2)

Eranga
Eranga

Reputation: 32447

You can override the SaveChanges method of your DbContext.

public override int SaveChanges()
{
    var deletedEntities = ChangeTracker.Entries().Where(entry => entry.State == EntityState.Deleted);

    foreach (var deletedEntity in deletedEntities)
    {
        if (deletedEntity .Entity is MyEntity)
        {
             //delete the file
        }
    }

    return base.SaveChanges();
}

You can wrap the file delete and database update in a single transaction as follows

using (var scope = new TransactionScope())
{
    //your deletion logic

    myContext.SaveChanges();

    scope.Complete();
}

Upvotes: 1

J-16 SDiZ
J-16 SDiZ

Reputation: 26910

Try doing it in a database level trigger. EF is not the proper place to handle this.

Upvotes: 0

Related Questions