【问题标题】:Delete item from database with C# using HttpDelete使用 C# 使用 HttpDelete 从数据库中删除项目
【发布时间】:2018-01-24 14:29:51
【问题描述】:

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

我正在通过这样的角度前端调用将项目传递给我的 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);

    }

我错过了什么?

【问题讨论】:

  • _context.SetModified 是什么?为什么不在 DbSet 上Remove?您还应该调用 SaveAsync 以保留更改。此外,您可能应该从 web api/mvc 方法返回一个结果,例如 200。
  • @Igor 我的 SetModified 方法 public virtual void SetModified&lt;T&gt;(T entity) where T : class { if (Entry(entity).State != EntityState.Modified) Entry(entity).State = EntityState.Modified; } 在枚举中设置 EntityState,其中 2 = 已删除,3 = 已修改

标签: c# entity-framework sql-delete http-delete


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-05-15
    • 2018-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-10
    • 2014-11-05
    相关资源
    最近更新 更多