简体   繁体   English

删除具有外键约束的记录

[英]Delete a record with a foreign key constraint

ASP.NET CORE 2.1 application ASP.NET CORE 2.1应用程序

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. ProductDescription表中存在对主键的引用。 I've tried the fluid api method of defining the foreign key. 我尝试了定义外键的Fluid API方法。 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 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". SqlException:DELETE语句与REFERENCE约束“ FK_ProductDescriptions_Product_ProductId”冲突。 The conflict occurred in database "FoodInventoryDB", table "dbo.ProductDescriptions", column 'ProductId'. 数据库“ FoodInventoryDB”的表“ dbo.ProductDescriptions”的列“ 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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