我正在尝试删除产品,但收到此错误消息。我知道我需要从库存表中删除外键,然后才能从产品表中删除产品。我试图在我的模型构建器中进行设置,但无法使其正常工作。对此有什么好的解决方案吗?
SqlException:DELETE语句与REFERENCE约束“ FK__Stock__ProductID__2E1BDC42”冲突。在数据库“库存”的表“ dbo.Stock”的“产品ID”列中发生了冲突。
这是我的InventoryContext
:
public virtual DbSet<Products> Products { get; set; }
public virtual DbSet<Stock> Stock { get; set; }
public virtual DbSet<Storage> Storage { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Products>(entity =>
{
entity.HasKey(e => e.ProductId);
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
entity.Property(e => e.Price).HasColumnType("decimal(18, 0)");
});
modelBuilder.Entity<Stock>(entity =>
{
entity.Property(e => e.StockId).HasColumnName("StockID");
entity.Property(e => e.ProductId).HasColumnName("ProductID");
entity.Property(e => e.StorageId).HasColumnName("StorageID");
entity.HasOne(d => d.Product)
.WithMany(p => p.Stock)
.HasForeignKey(d => d.ProductId)
.HasConstraintName("FK__Stock__ProductID__2E1BDC42");
entity.HasOne(d => d.Storage)
.WithMany(p => p.Stock)
.HasForeignKey(d => d.StorageId)
.HasConstraintName("FK__Stock__StorageID__2F10007B");
});
modelBuilder.Entity<Storage>(entity =>
{
entity.Property(e => e.StorageId).HasColumnName("StorageID");
entity.Property(e => e.Name)
.IsRequired()
.HasMaxLength(100)
.IsUnicode(false);
});
}
}
}
这是我在控制器中的方法
public async Task<IActionResult> DeleteConfirmed(long id)
{
var products = await _context.Products.FindAsync(id);
_context.Products.Remove(products);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}