我是 .NET 和 Entity Framework Core (v8) 的新手,我想知道是否有一种方法可以为以下内容配置级联删除
场景:
当我删除
File
实体(数据库行)时,我希望所有关联的实体也被删除。目前,当我尝试删除文件实体时遇到外键错误。
public class File
{
public Guid Id { get; set; }
public string? Name { get; set; }
public string? Type { get; set; }
public DateTime UploadedDate { get; set; }
public string UploadedBy { get; set; }
public string? FileUrl { get; set; }
public FileType FileType { get; set; }
}
public class Entity1
{
public Guid Id { get; set; }
public Guid? FileId { get; set; }
public File? File { get; set; }
}
public class Entity2
{
public Guid Id { get; set; }
public Guid? FileId { get; set; }
public File? File { get; set; }
}
public class Entity3
{
public Guid Id { get; set; }
public Guid? FileId { get; set; }
public File? File { get; set; }
}
public async Task Delete(Guid fileId)
{
var file = await _dbContext.FileMetadatas
.FirstOrDefaultAsync(sr => sr.Id == fileId);
var fileInfo = new FileInfo(file.FileUrl);
_dbContext.FileMetadatas.Remove(file);
await _dbContext.SaveChangesAsync();
if (fileInfo.Exists)
{
fileInfo.Delete();
}
}
将其添加到您的 dbContext 文件中:
OnDelete(DeleteBehavior.Cascade)
如下图
public class MyDbContext : DbContext
{
public DbSet<File> Files { get; set; }
public DbSet<Entity1> Entity1s { get; set; }
public DbSet<Entity2> Entity2s { get; set; }
public DbSet<Entity3> Entity3s { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<File>()
.HasMany(f => f.Entity1s)
.WithOne(e => e.File)
.HasForeignKey(e => e.FileId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<File>()
.HasMany(f => f.Entity2s)
.WithOne(e => e.File)
.HasForeignKey(e => e.FileId)
.OnDelete(DeleteBehavior.Cascade);
modelBuilder.Entity<File>()
.HasMany(f => f.Entity3s)
.WithOne(e => e.File)
.HasForeignKey(e => e.FileId)
.OnDelete(DeleteBehavior.Cascade);
}
}
配置关系后,您可以删除文件,所有相关实体也将被删除。