2

Code

public IActionResult CreateVacancy([FromBody] VacancyDTO vacancyDTO)
{
    if (vacancyDTO == null)
        return BadRequest(ModelState);

    var existed = _vacancyRepository.GetVacancyByTitle(vacancyDTO.Title);

    if (existed != null)
    {
        ModelState.AddModelError("Existed", "Vacancy with this title already existed");
        return StatusCode(422, ModelState);
    }

    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }

    var vacancy = _mapper.Map<Vacancy>(vacancyDTO);

    if (!_vacancyRepository.CreateVacancy(vacancy))
    {
        ModelState.AddModelError("Not Created", "Failed To Create");
        return StatusCode(500, ModelState);
    }

    return Ok("Successfully created");
}

When I try to insert a new vacancy, I got this error:

SqlException: Cannot insert explicit value for identity column in table 'Employers' when IDENTITY_INSERT is set to OFF.

Even if I insert in vacancies table that depends on employerId and when I insert a new vacancy, I provide an employerId value that exists.

public bool CreateVacancy(Vacancy vacancy)
{
    _context.Vacancies.Add(vacancy);
    return Save();
}

1 Answer 1

2

There is an Employer in your DbContext change tracker in "Added" state. This is the default when you attach an entity graph. But this Entity should be set to "Unchanged" so EF won't try to insert it.

Not the answer you're looking for? Browse other questions tagged or ask your own question.