ASP.NET Core Web API - POST方法抛出重复(自动增量)PK的异常

时间:2017-05-02 11:59:33

标签: 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 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 }); 
            }
        }

上面的代码工作正常,并为给定的人添加新的Tutor到数据库,为Tutor实体生成正确的TutorId。但是,当我将newTutor.Person = personnewTutor.PersonId = vmTutor.PersonId的关联更改为停止工作并抛出异常时,如下所示:

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操作?

请求帮助和解释。

0 个答案:

没有答案