删除具有外键约束的记录

时间:2018-09-06 22:19:11

标签: c# asp.net-core-2.1

ASP.NET CORE 2.1应用程序

大家好,

我有一个项目,当我尝试删除记录时会引发错误。 ProductDescription 表中存在对主键的引用。我尝试了定义外键的Fluid API方法。我要去哪里错了?

型号

public class Product
{

   [Key]
    public int Id { get; set; }
    public string ProductName { get; set; }
    public string Price { get; set; }

    public ProductDescription ProductDescriptions {get; set;}
}


public class ProductDescription
{
   public int DescriptionId { get; set; }
   public string Amount     { get; set; }
   public string Colour     { get; set; }

   public Product Product   { get; set; }
} 

控制器

public async Task<IActionResult> Delete(int? id)
{
    if (id == null) return NotFound();

    var products = await _context.Product
        .SingleOrDefaultAsync(m => m.Id == id);

    if (products == null) NotFound();

    return View(products);
}


[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    var product = await _context.Product.SingleOrDefaultAsync(m => m.Id == id);
    _context.Product.Remove(product);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

ApplicationDbContext

protected override void OnModelCreating(ModelBuilder builder)
{
    builder.Entity<Product>()
        .HasOne(s => s.ProductDescription)
        .WithMany()
        .OnDelete(DeleteBehavior.Cascade);

    base.OnModelCreating(builder);
}
public DbSet<Product> Products { get; set; }
public DbSet<ProductDescription> ProductDescriptions  { get; set; }

异常错误

  

处理请求时发生未处理的异常。   SqlException:DELETE语句与REFERENCE约束“ FK_ProductDescriptions_Product_ProductId”冲突。数据库“ FoodInventoryDB”的表“ dbo.ProductDescriptions”的列“ ProductId”中发生了冲突。   该声明已终止。

1 个答案:

答案 0 :(得分:0)

所以我终于解决了它。希望这对其他人有帮助...

这就是我所做的:

[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public async Task<IActionResult> DeleteConfirmed(int id)
{
    var product = await _context.Product.SingleOrDefaultAsync(m => m.Id == id);
    var stuff = await _context.ProductDescription.FirstOrDefaultAsync(c => c.Product.Id == id);
    _context.Product.Remove(product);
    _context.ProductDescription.Remove(stuff);
    await _context.SaveChangesAsync();
    return RedirectToAction(nameof(Index));
}

   builder.Entity<Product>()
        .HasMany(s => s.ProductDescription)
        .WithOne(c = c.Product)
        .OnDelete(DeleteBehavior.Cascade);