简体   繁体   中英

Delete a record with a foreign key constraint

ASP.NET CORE 2.1 application

Hello all,

I have a project that throws an error when I try to delete a record. References to the primary key exists within the ProductDescription table. I've tried the fluid api method of defining the foreign key. Where am I going wrong?

Model

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; }
} 

Controller

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; }

Exception Error

An unhandled exception occurred while processing the request. SqlException: The DELETE statement conflicted with the REFERENCE constraint "FK_ProductDescriptions_Product_ProductId". The conflict occurred in database "FoodInventoryDB", table "dbo.ProductDescriptions", column 'ProductId'. The statement has been terminated.

So I finally fixed it. Hope this helps others...

This is what I did:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM