'How to remove nested object with EF. ASP.NET MVC 5

I have admin page and have a logic to delete item but for some reason it doesn't work. I have model "Item" and "CartItem".

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 Item Item { get; set; }
        public int? UserId { get; set; }
        [ForeignKey("UserId")]
        public User User { get; set; }
        public int Quantity { get; set; }
    }

Controller

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteItemPost(int id)
        {
            var item = await _itemRepo.ReadByIdAsync(id);
            if (item == null)
            {
                return NotFound();
            }

            await _itemRepo.DeleteAsync(item);
            return RedirectToAction("ReadItems");
        }

When i check with debugger everything works fine but item is still in database. After long time of searching i thought that problem was the "CartItem" Model, because "Item" is connected with foreign key. So i am not sure what is the problem here, i don't get any exceptions, any errors or something like that, everything works fine but the object doesn't remove

Repository

using Microsoft.EntityFrameworkCore;
using RandApp.Data;
using RandApp.Models;
using RandApp.Repositories.Abstraction;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace RandApp.Repositories
{
    public class Repository<T> : IRepository<T> where T : BaseEntity
    {
        private readonly ApplicationDbContext _db = default;
        private readonly DbSet<T> _entity = default;
        public Repository(ApplicationDbContext db)
        {
            _db = db;
            _entity = _db.Set<T>();
        }
        public async Task<bool> CreateAsync(T item)
        {
            _entity.Add(item);
            return await SaveChangesAsync();
        }

        public async Task<bool> DeleteAsync(T item)
        {
            _entity.Remove(item);
            return await SaveChangesAsync();
        }

        public async Task<IEnumerable<T>> ReadAsync()
        {
            return await _entity.ToListAsync();
        }

        public async Task<T> ReadByIdAsync(int? id)
        {
            return await _entity.FirstOrDefaultAsync(o => o.Id == id);
        }

        public async Task<bool> UpdateAsync(T item)
        {
            _entity.Update(item);
            return await SaveChangesAsync();
        }

        public async Task<bool> SaveChangesAsync()
        {
            try
            {
                return (await _db.SaveChangesAsync()) >= 0;
            }
            catch
            {
                return false;
            }
        }

        public DbSet<T> Get()
        {
            return _entity;
        }
    }
}



Solution 1:[1]

I see the codes swallows the exception via the try/catch in SavesChangesAsync and returns false. I would do the following:

  1. Nuke the try/catch. Or, log any exceptions so there is visibility
  2. Check the return value. If the value is false, something is wrong with the db connection

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 beautifulcoder