【问题标题】:How to add data and remove same data from other table in asp.net core?如何在 asp.net core 的其他表中添加数据和删除相同的数据?
【发布时间】:2020-07-26 20:48:20
【问题描述】:

我正在尝试从添加到 TestResult 表中的现有表 PendingTestResult 中删除同一行。但它不起作用请帮我解决这个问题

这是控制器

 [HttpPost]
    [Route("Reception/PatientTests/SaveTestResult")]
    public async Task<IActionResult> SaveTestResult(List<TestResult> testResults)
    {
        if (ModelState.IsValid)
        {
            foreach (TestResult tr in testResults)
            {
                _db.Add(tr);
                await _db.SaveChangesAsync();
                var TestResultId = new PendingTestResult { Id = tr.Id };
                _db.Remove<PendingTestResult>(TestResultId);
                await _db.SaveChangesAsync();
            }

            // return new JsonResult("Index");
        }

        return new JsonResult(testResults); ;
    }

这里我想从 TestResult 表中新添加的 PendingTestResult 表中删除相同的行。

【问题讨论】:

    标签: asp.net-core entity-framework-core asp.net-core-2.0


    【解决方案1】:

    请确保您要删除的数据在表格中可用。
    我建议不要创建新对象,而是使用 Find 方法
    假设 _db 是 DbContext 的对象。

     _db.Add(tr);
     _db.PendingTestResults.Remove(_db.PendingTestResults.Find(tr.Id));
      await _db.SaveChangesAsync();
    

    请更改 DbSet 属性名称。

    如果要调试代码,请使用 sql server profiler。

    【讨论】:

    • 我通过更改此代码 _db.Add(tr); 解决了这个问题_db.pendingTestResults.Remove(_db.pendingTestResults.Where(p=>p.PatientId==tr.PatientId).FirstOrDefault());等待_db.SaveChangesAsync();
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2020-06-16
    • 2020-03-19
    • 2019-11-17
    • 1970-01-01
    • 2021-07-08
    • 1970-01-01
    相关资源
    最近更新 更多