微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如果存在关系则防止删除-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 的逻辑。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。