簡體   English   中英

刪除具有外鍵約束的記錄

[英]Delete a record with a foreign key constraint

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”中發生了沖突。 該語句已終止。

所以我終於解決了。 希望這對其他人有幫助...

這是我所做的:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM