CodyCS CodyCS - 1 month ago 17
C# Question

Delete item from database with C# using HttpDelete

I am trying to delete a row from my database based on a Primary Key ID field. When I try to do it, all of the code executes without any errors, but the item doesn't get deleted from the database.

I'm passing the item to my C# backend from an angular frontend call like this:

delete(customerId: number, materialCustomerId: number): Observable<Response> {
return this.http.delete(`${this.getBaseUrl()}/${customerId}/materialcustomer/${materialCustomerId}`).catch(error => this.handleError(error));
}


It then hits my controller method:

[HttpDelete]
[Route("{customerId}/materialcustomer/{materialCustomerId}")]
[AccessControl(Securable.Customer, Permissions.Delete, Permissions.Execute)]
public async Task Delete(int customerId, int materialCustomerId)
{
await _materialCustomerDeleter.DeleteAsync(MaterialCustomer.CreateWithOnlyId(materialCustomerId), HttpContext.RequestAborted);
}


Manipulator method:

public async Task DeleteAsync(MaterialCustomer model, CancellationToken cancellationToken = default(CancellationToken))
{
if (model == null)
throw new ArgumentNullException(nameof(model));

await _materialCustomerDeleter.DeleteAsync(new TblMaterialCustomer { MaterialCustomerId = model.MaterialCustomerId }, cancellationToken);

if (cancellationToken.IsCancellationRequested)
return;

await _customerWriter.CommitAsync(cancellationToken);
}


and finally, my repository method:

public async Task DeleteAsync(TblMaterialCustomer entity, CancellationToken cancellationToken = new CancellationToken())
{
var item =
await _context.TblMaterialCustomer.FirstOrDefaultAsync(i => i.MaterialCustomerId == entity.MaterialCustomerId, cancellationToken);

if (item == null || cancellationToken.IsCancellationRequested)
return;

_context.SetModified(item);

}


What am I missing?

Answer Source

Assuming that await _customerWriter.CommitAsync(cancellationToken); calls through to the same DbContext instance and calls method SaveAsync you should re-write the delete method like this:

public void Delete(TblMaterialCustomer entity)
{
    _context.TblMaterialCustomer.Remove(entity);
}

Also it would probably be a good idea to return a result from the WebAPI call, although it is not required, like OK/200.

public async Task<IHttpActionResult> Delete(int customerId, int materialCustomerId)
{
    await _materialCustomerDeleter.DeleteAsync(MaterialCustomer.CreateWithOnlyId(materialCustomerId), HttpContext.RequestAborted);
    return Ok();
}