I'm new to .NET and Entity Framework Core (v8), and I'm wondering if there's a way to configure cascade deletion for the following
scenario:
When I delete a File
entity (database row), I want all associated entities to be deleted as well. Currently, I'm encountering a foreign key error when I attempt to delete a File entity.
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();
}
}
Add this in your dbContext file:
OnDelete(DeleteBehavior.Cascade)
As shown bellow
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);
}
}
After configuring the relationships, you can delete a File and all related entities will be deleted as well.