模型OnDelete事件?

时间:2012-09-05 05:18:51

标签: entity-framework asp.net-mvc-4

我有一个看起来像这样的简单模型:

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; }
}

有什么方法可以添加某种“OnDelete”事件挂钩,这样每当通过db.Images.Remove(imageFile);或其他任何方式删除模型时,我都可以删除相关文件吗?

1 个答案:

答案 0 :(得分:3)

您可以覆盖上下文的SaveChanges方法以挂钩删除实体。

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();
     }
}