C# ASP.NET核心Web API-POST方法引发重复(自动递增)PK异常
我在这样的代码中遇到了奇怪的行为:C# ASP.NET核心Web API-POST方法引发重复(自动递增)PK异常,c#,asp.net-core,entity-framework-core,C#,Asp.net Core,Entity Framework Core,我在这样的代码中遇到了奇怪的行为: // POST: /tutors [HttpPost] public async Task<IActionResult> CreateTutor([FromBody] TutorViewModel vmTutor) { if (vmTutor == null) return new StatusCodeResult(500); // Internal Ser
// POST: /tutors
[HttpPost]
public async Task<IActionResult> CreateTutor([FromBody] TutorViewModel vmTutor) {
if (vmTutor == null)
return new StatusCodeResult(500); // Internal Server Error
try
{
// check if the Person with given personId exists
Person person = await _unitOfWork.People.GetAsync(vmTutor.PersonId);
if (person == null) throw new Exception("Given Person doesn't exists.");
// create new Tutor entity for given Person entity
var newTutor = new Tutor
{
Description = vmTutor.Description,
Qualifications = vmTutor.Qualifications,
IsSuperTutor = vmTutor.IsSuperTutor,
//PersonId = vmTutor.PersonId
Person = person
};
// Add new Tutor to DBContext and save changes
await _unitOfWork.Tutors.AddAsync(newTutor);
_unitOfWork.Complete();
vmTutor.TutorId = newTutor.TutorId;
return CreatedAtAction(nameof(GetTutor), new { tutorId = vmTutor.TutorId }, vmTutor);
} catch(Exception e) {
return new ObjectResult(new { error = e.Message });
}
}
正如我所记得的,当存在其非异步版本时,相同的代码可以正常工作,即如下所示:
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details. ---> System.Data.SqlClient.SqlException: Cannot insert duplicate key row in object 'dbo.Tutors' with unique index 'IX_Tutors_PersonId'. The duplicate key value is (6).
The statement has been terminated.
// POST: /tutors
[HttpPost]
public IActionResult CreateTutor([FromBody] TutorViewModel vmTutor) {
if (vmTutor == null)
return new StatusCodeResult(500); // Internal Server Error
try
{
// check if the Person with given personId exists
Person person = _unitOfWork.People.Get(vmTutor.PersonId);
if (person == null) throw new Exception("Given Person doesn't exists.");
// create new Tutor entity for given Person entity
var newTutor = new Tutor
{
Description = vmTutor.Description,
Qualifications = vmTutor.Qualifications,
IsSuperTutor = vmTutor.IsSuperTutor,
PersonId = vmTutor.PersonId
//Person = person
};
// Add new Tutor to DBContext and save changes
_unitOfWork.Tutors.AddAsync(newTutor);
_unitOfWork.Complete();
vmTutor.TutorId = newTutor.TutorId;
return CreatedAtAction(nameof(GetTutor), new { tutorId = vmTutor.TutorId }, vmTutor);
} catch(Exception e) {
return new ObjectResult(new { error = e.Message });
}
}
您能解释一下为什么我在使用异步版本时不能直接在Tutor实体中分配外键PersonId吗?并向我解释什么时候应该首选此异步版本而不是临时的实体CRUD操作
谢谢你的帮助和解释 例外情况没有提到与您的PK冲突。它在似乎是唯一索引的IX_Tutors_PersonId上抛出错误。通常PK或FK是唯一的?但数据库中并没有像PersonId这样具有键值的记录。使用具有相同id的Person对象关联时的插入可以正常工作。我还记得,当没有这个异步/等待修饰符和使用_unitOfWork.People.GetAsync()方法显式检查数据库中的人员存在时,这个方法可以很好地工作