c# - 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 }
}
解决方案
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();
}
推荐阅读
- javascript - Javascript记忆游戏图片不转
- r - 在 RStudio 中创建新的 Shiny 应用程序时如何更改加载的模板?
- powerbi - POWER BI如何比较两个数据
- html - 如何在不损坏图像的情况下将图像添加到 Bootstrap navbar-brand?
- authentication - 使用 Formik 确认密码
- excel - Excel:Power Query 编辑器:来自 Web 的数据源具有更改的列
- powerbi - Power BI - 过滤计数未按表中的值分组
- customization - Acumatica - 操作“撤消并应用备忘录”默认过帐期间到活动财务期间
- java - Java Protobuf 编译器:公共字段
- react-native - 关于配额 youtube 数据 api 的问题