【问题标题】:Prevent deletion if relationship exist - Fluent API如果存在关系,则防止删除 - Fluent API
【发布时间】:2020-10-09 14:05:12
【问题描述】:

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

在我编写的代码中,它允许删除。当我删除一个类别时,它也会删除关联的产品。 我想让我的代码做的是,如果有相应的记录,我会阻止我删除一个类别。

谁能帮我解决这个问题。

类别

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 映射关系

类别配置

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);

    }
}

产品配置

    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);
    }
}

【问题讨论】:

    标签: entity-framework .net-core ef-fluent-api


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多