使用 C# 使用 HttpDelete 从数据库中删除项目

Delete item from database with C# using HttpDelete

我正在尝试根据主键 ID 字段从我的数据库中删除一行。当我尝试这样做时,所有代码都没有任何错误地执行,但该项目没有从数据库中删除。

我正在将项目从 angular 前端调用传递到我的 C# 后端,如下所示:

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

然后它会触发我的控制器方法:

    [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);
    }

操纵器方法:

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);
    }

最后,我的存储库方法:

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);

    }

我错过了什么?

假设 await _customerWriter.CommitAsync(cancellationToken); 调用相同的 DbContext 实例并调用方法 SaveAsync 您应该像这样重写删除方法:

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

此外,return WebAPI 调用的结果可能是个好主意,尽管这不是必需的,例如 OK/200。

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