Home > Enterprise >  How to delete object which is connected to another model with FK. ASP.NET Core MVC
How to delete object which is connected to another model with FK. ASP.NET Core MVC

Time:02-22

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.

CodePudding user response:

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

var cartItems= _entity.Set<CartItem>().Where(i=> i.ItemId == item.Id).ToArray();

    if(cartItems!=null) 
          foreach(var cartItem in cartItems) cartItem.ItemId=null;

    _entity.Set<Item>().Remove(item);

    return await SaveChangesAsync();
}

CodePudding user response:

Adding [Required] would force cascade delete

public class CartItem : BaseEntity
{
    public int? ItemId { get; set; }
    [Required]
    [ForeignKey("ItemId")]
    public Item Item { get; set; }
}

Or using Fluent API you can configure WillCascadeOnDelete(true) to cascade delete.

  • Related