Home > Mobile >  Trying to delete from database using HTTPDELETE does nothing
Trying to delete from database using HTTPDELETE does nothing

Time:01-23

I am learning to code in c# and I am developing an API application. My GET method works but I have issues with my DELETE, it returns a success code(200) but it does not delete from my database which is connected to my application. I am using the unit of work and repository patterns and my code is as follows:

Controller code:

        private readonly IOrderService _orderService;

        public OrdersController(IOrderService orderService)
        {
            _orderService = orderService;         
        }

[HttpDelete("{id}")]
        public async Task<ActionResult> RemoveOrder(int id)
        {
            try
            {
                await _orderService.Delete(id);
                return StatusCode(200);
            }
            catch (Exception ex)
            {
                return StatusCode(500);
            }

        }

Service Interface

public interface IOrderService
    {
        Task<Order> Get(int id);
        Task Add(Order order);
        Task Delete(int id);
        Task Update(int id, Order order);

        Task<IEnumerable<Order>> GetAllOrdersAsync();
        Task<IEnumerable<OrderDTO>> GetOrdersToCityAsync(string cityName);

        Task<OrderDTO> GetEmployeeOrdersToCountryAsync
    (
    string countryName, string employeeLastName
    );
    }

Service class:

 public class OrderService : IOrderService
    {
        private readonly IUnitOfWork _unitOfWork;
        public OrderService(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
        public async Task Delete(int id)
        {
            try
            {
                var order = await _unitOfWork.OrderRepository.Get(id);
                _unitOfWork.OrderRepository.Delete(order);
                await _unitOfWork.CommitAsync();
            }
            catch (Exception e)
            {
                await _unitOfWork.RollbackAsync();
                throw;
            }
            
        }
}

Unit of work class:

public class UnitOfWork : IUnitOfWork
    {
        private readonly NorthwindContext _db;
        private List<object> _customRepositories = new List<object>();
        private IProductRepository _productRepository;
        private IOrderRepository _orderRepository;
        public UnitOfWork(
            NorthwindContext db, 
            IProductRepository ProductRepository,
            IOrderRepository orderRepository
            )
        { 
            _db = db;
            _productRepository = ProductRepository;
            _orderRepository = orderRepository;
        }

uow interface:

    public interface IUnitOfWork
    {
        IProductRepository ProductRepository { get; }

        IOrderRepository OrderRepository { get; }
        Task CommitAsync();
        Task RollbackAsync();
    }


Order repository interface which extends my genericRepository:

    public interface IOrderRepository : IGenericRepository<Order>
    {
        Task<IEnumerable<OrderDTO>> GetOrdersToCityAsync(string cityName);

        Task<OrderDTO> GetEmployeeOrdersToCountryAsync
            (
            string countryName, string employeeLastName
            );
    }

Order repository:

   public class OrderRepository : GenericRepository<Order>, IOrderRepository
    {
        private readonly NorthwindContext _northwindContext;
        public OrderRepository(NorthwindContext db) : base(db)
        {
            _northwindContext = db;
        }

generic repository:

    public class GenericRepository<T> : IGenericRepository<T> where T : class
    {
        protected readonly NorthwindContext _db;

        public GenericRepository(NorthwindContext db)
        {
            _db = db;
        }


        public void Delete(T entity)
        {
            _db.Set<T>().Remove(entity);
        }

Please ignore if the curly braces are not closed properly, in my application they are.

CodePudding user response:

Please check the following items:

  • Unit of work implementation calls SaveChanges() on CommitAsync implementation.
  • NorthwindContext object instance passed to repositories is the same instance as the one injected into UnitOfWork class. Otherwise you'll be working in different transactions.

CodePudding user response:

You could delete an entry from database while using the following code.

    [HttpDelete{"id"}]
    Public async<Task<ActionResult>> DeleteItem (int id)
    { try{
    Var itemToDelete = await UnitofWork.OrderRepository.GetAsync(id);
    If (Id!= null) {
    await Orderservice.Delete(itemToDelete);
    var result  = await UnitofWork.SaveChangesAsync();
    If (result) return StatusCode(200);
    Else return BadRequest();
    return ok(itemToDelete);
    } catch(exception ex) {
Throw new Error("Problem while deleting!");
}
    Return BadRequest();
    }
    }

Just check if the item you would want ro delete is null or not. Then attempt to delete it from database. Hoping it would give you an idea.

  • Related