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



类别和产品之间存在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);
}
}

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

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

最新更新