There is the error: The DELETE statement conflicted with the REFERENCE constraint "FK_ShoppingCartItems_ItemsTable_ItemId". The conflict occurred in database "RandDb", table "dbo.ShoppingCartItems", column ‘ItemId’. The statement has been terminated.
Item
public class Item : BaseEntity
{
[Required]
[Display(Name = "Item Photo")]
public string ItemPhoto { get; set; }
[Required]
[Display(Name = "Item Type")]
public string ItemType { get; set; }
[Required]
[Display(Name = "Item Name")]
public string Name { get; set; }
[Required]
[Display(Name = "Item Color")]
public string Color { get; set; }
[Required]
[Display(Name = "Item Size")]
public string Size { get; set; }
[Required]
[Display(Name = "Item Material Type")]
public string MaterialType { get; set; }
[Required]
[Display(Name = "Designed For")]
public string DesignedFor { get; set; }
[Required]
[Display(Name = "Item Price")]
public double Price { get; set; }
[Required]
[Display(Name = "Item Description")]
public string Description { get; set; }
}
CartItem
public class CartItem : BaseEntity
{
public int? ItemId { get; set; }
[ForeignKey("ItemId")]
public Item Item { get; set; }
public int? UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
public int Quantity { get; set; }
}
Repository
public async Task<bool> DeleteAsync(T item)
{
_entity.Remove(item);
return await SaveChangesAsync();
}
public async Task<bool> SaveChangesAsync()
{
try
{
return (await _db.SaveChangesAsync()) >= 0;
}
catch
{
return false;
}
}
I want to do the following: so I have an admin page from where i make crud operations, i also have shopping cart where user can add items, so when any item is added in cart of any user, it doesn’t delete, it throws the error which i mentioned above. so what can i do to remove shopping cart items, when admin deletes this item from admin page.
2
Answers
Delete is getting tricky when you have foreign keys, So I don’t recomend you to use a generic repository. you can try this code
Adding
[Required]
would force cascade deleteOr using Fluent API you can configure
WillCascadeOnDelete(true)
to cascade delete.