开发者

OnDelete also delete file

开发者 https://www.devze.com 2023-03-27 17:10 出处:网络
Using EF4.1is 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 fil

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号