如果存在关系则防止删除-Fluent API

问题描述

类别和产品之间存在One to Many关系。一个类别将有许多产品。但是,当我尝试删除类别时,如果有带有该类别的产品,则不应允许我这样做。

在我编写的代码中,它允许删除。当我删除类别时,它也会同时删除关联的产品。 我要我的代码执行的操作是,防止有相应记录的情况下删除Catergory。

有人可以帮我解决这个问题吗?

类别

public class Catergory
{
    public int CatergoryId { get; set; }
    public string CatergoryName { get; set; }
    public string CatergoryDescription { get; set; }

    public ICollection<Product> Products { get; set; }

}

产品

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public string ProductDescription { get; set; }
    public int CatergoryID { get; set; }

    public Catergory Catergory { get; set; }
}

使用Fluent API映射关系

CatergoryConfiguration

class CatergoryConfiguration : IEntityTypeConfiguration<Catergory>
{
    public void Configure(EntityTypeBuilder<Catergory> builder)
    {
        builder.ToTable("Catergory");

        builder.HasKey(c => c.CatergoryId);

        builder.Property(c => c.CatergoryName)
            .IsRequired(true)
            .HasMaxLength(400);

        builder.Property(c => c.CatergoryDescription)
            .IsRequired(true);

    }
}

ProductConfig

    public void Configure(EntityTypeBuilder<Product> builder)
    {
        builder.ToTable("Product");

        builder.HasKey(p => p.ProductID);

        builder.Property(p => p.ProductName)
            .HasMaxLength(400)
            .IsRequired(true);

        builder.Property(p => p.ProductDescription)
            .HasMaxLength(2000)
            .IsRequired(true);

        builder.HasOne(f => f.Catergory)
            .WithMany(r => r.Products)
            .HasForeignKey(f => f.CatergoryID);
            .OnDelete(DeleteBehavior.Restrict);
    }
}

解决方法

很遗憾,您无法在 FluentAPI 中进行配置。 OnDelete 仅设置删除主体实体时如何处理相关实体的行为。

在您的删除方法中,您需要包含在删除前检查 Category 是否具有 Products 的逻辑。

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...