大家好,
我有一个项目,当我尝试删除记录时会引发错误。 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));
}
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”中发生了冲突。 该声明已终止。
答案 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);