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

Viewed 72

i am getting this error SqlException: Cannot insert explicit value for identity column in table 'Ogretmenler' when IDENTITY_INSERT is set to OFF. Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, bool breakConnection, Action wrapCloseInAction)

DbUpdateException: An error occurred while saving the entity changes. See the inner exception for details. Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.Execute(IRelationalConnection connection

what should i do?

here is my code

[HttpGet]

    public IActionResult Create()
    {
        List<SelectListItem> value = (from Ders in _db.Dersler.ToList()
                                      select new SelectListItem
                                      {
                                          Text = Ders.DersName,
                                          Value = Ders.Id.ToString()
                                      }).ToList();
        ViewBag.v1 = value;


        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public IActionResult Create(Ogretmen obj)
    {
        if (ModelState.IsValid)
        {
            _db.Ogretmenler.Add(obj);
            _db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(obj);
    } 
1 Answers

The exception 'Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF' is thrown when you attempt to insert a value in the Identity Column.

Either:

  • Make sure the object you add to the db does not have a value for the ID field.

or

  • Turn on Identity insert if you want to be able to insert the ID manually with 'SET IDENTITY_INSERT Ogretmenler ON'.
Related