I use Visual Studio 2013 with Sql Server 2012. I use this to generate views for my project. I have two tables:
- UTILISATEUR (ID_UTILISATEUR,CIN,NOM,PRENOM...,ID_ROLE):
ID_UTILISATEUR is primary key and ID_ROLE is the foreign key. - ROLE (ID_ROLE, NOM_ROLE, DESCRIPTION_ROLE): ID_ROLE is the primary key.
After the code generation process is complete, I have this:
- Controllers/UtilisateurController.cs .
- A new folder (Views/Utilisateur) : Create.cshtml, Delete.cshtml, Details.cshtml, Edit.cshtml and Index.cshtml .
My problem is that when I access to the Create.cshtml page, remply the fields and click Create I get the error: Cannot insert explicit value for identity column in table 'UTILISATEUR' when IDENTITY_INSERT is set to OFF.
It explains that I can't insert values to the identity column because it is set on ON. I don't know what I should change in the following code to resolve it.
My Create method in UtilisateurController.cs :
public ActionResult Create()
{
ViewBag.ID_ROLE = new SelectList(db.ROLE, "ID_ROLE", "NOM_ROLE");
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include="ID_UTILISATEUR,CIN_UTILISATEUR,MATRICULE_UTILISATEUR,NOM_UTILISATEUR,PRENOM_UTILISATEUR,PASSWORD_UTILISATEUR,MAIL_UTILISATEUR,TELEPHONE_UTILISATEUR,ID_ROLE")] UTILISATEUR utilisateur)
{
if (ModelState.IsValid)
{
db.UTILISATEUR.Add(utilisateur);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.ID_ROLE = new SelectList(db.ROLE, "ID_ROLE", "NOM_ROLE", utilisateur.ID_ROLE);
return View(utilisateur);
}
The error line is: db.SaveChanges();
My Views/Utilisateur/Create.cshtml page is:
....
@Html.ValidationSummary(true)
<div class="form-group">
@Html.LabelFor(model => model.ID_UTILISATEUR, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.EditorFor(model => model.ID_UTILISATEUR)
@Html.ValidationMessageFor(model => model.ID_UTILISATEUR)
</div>
</div>
<div class="form-group">
<label for="inputCIN" class="control-label col-xs-2">CIN</label><div class="col-md-10">
@Html.EditorFor(model => model.CIN_UTILISATEUR)
@Html.ValidationMessageFor(model => model.CIN_UTILISATEUR)
</div>
</div>.....
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="submit" value="créer" class="btn btn-default" />
</div>....
Please help !