如何在 Entity Framework Core 8 中配置级联删除

问题描述 投票:0回答:1

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

c# .net entity-framework-core foreign-keys cascade
1个回答
0
投票

将其添加到您的 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);
        }
    }

配置关系后,您可以删除文件,所有相关实体也将被删除。

© www.soinside.com 2019 - 2024. All rights reserved.