首页 > 解决方案 > ASP.NET Core 模型是否有类似 OnDelete 回调的东西?

问题描述

我有以下模型:

 public class MyFiles
    {
        public int MyFilesId { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }
    }

如您所见,它是上传文件的模型。每个模型都保留路径wwwroot/ ...和文件(例如图像)名称。但是当我删除这个模型时如何删除文件呢?我是说:

var res = _applicationDbContext.MyFiles.FirstOrDefault(x => x.MyFilesId = 666);
_applicationDbContext.MyFiles.Remove(res);
_applicationDbContext.SaveChanges();

当然,上面的代码不会删除文件。如果我可以编写如下内容,那将非常有用:

 public class MyFiles
    {
        public int MyFilesId { get; set; }
        public string Name { get; set; }
        public string Path { get; set; }

        protected OnDelete() { // here is logic for removing the file from OS }
    }

标签: c#.net-coreentity-framework-core

解决方案


EF 中没有可订阅的事件机制。你可以做的就是覆盖这里SaveChanges描述的

描述的是以下内容的变体:

public interface IFileSystemEntity
{
      string Path { get; set; }
}

public class MyFiles: IFileSystemEntity
{
    public int MyFilesId { get; set; }
    public string Name { get; set; }
    public string Path { get; set; }

    protected OnDelete() { // here is logic for removing the file from OS }
}

然后在你的 DBContext

public override int SaveChanges()
{
    this.ChangeTracker.DetectChanges();
    var added = this.ChangeTracker.Entries()
                .Where(t => t.State == EntityState.Deleted)
                .Select(t => t.Entity)
                .ToArray();

    foreach (var entity in added)
    {
        if (entity is IFileSystemEntity)
        {
            var track = entity as IFileSystemEntity;
            // Remove logic here
        }
    }
    return base.SaveChanges();
}

推荐阅读