【发布时间】: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