Using EF4.1 is there a event of function I can override on my POCO th开发者_如何学JAVAat 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.
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();
}
Try doing it in a database level trigger. EF is not the proper place to handle this.
精彩评论