0

I have an entity defined as in a db First Model:

public class Merlin_BR_Condiciones_Item
{
 public int IntIdGrupoCondiciones { get; set; }
 public string StrCondicion { get; set; }
 [Key]
 public int IntIdCondicion { get; set; }

 public virtual Merlin_BR_Condiciones_Item_Grupos Merlin_BR_Condiciones_Item_Grupos { get; set; }
}

And A controller generated automatically that has this create action:

public ActionResult Create(int pIntIdGrupoCondiciones = 0 )
{
   ViewBag.IntIdGrupoCondiciones = new SelectList(db.Merlin_BR_Condiciones_Item_Grupos, "IntIdGrupoCondiciones", "StrDescripcionGrupo");
   return View();
}
[HttpPost]
public ActionResult Create(Merlin_BR_Condiciones_Item merlin_br_condiciones_item)
{
     if (ModelState.IsValid)
     {
         //================================================================================
         // This section add the current key to IntIdCondicion 
         //================================================================================
         var max = from c in db.Merlin_BR_Condiciones_Item
                  select c;
         merlin_br_condiciones_item.IntIdCondicion = max.AsQueryable().Max(x => x.IntIdCondicion) + 1;
         //================================================================================

         db.Merlin_BR_Condiciones_Item.Add(merlin_br_condiciones_item);
         db.SaveChanges();
         return RedirectToAction("Index");  
     }

    ViewBag.IntIdGrupoCondiciones = new SelectList(db.Merlin_BR_Condiciones_Item_Grupos, "IntIdGrupoCondiciones", "StrDescripcionGrupo", merlin_br_condiciones_item.IntIdGrupoCondiciones);
     return View(merlin_br_condiciones_item);
}

This Entity has an Id Column assigned manually in the HttPost (create action). The problem is that an error was idicating me that Can't insert NULL Value in IntIdCondicion column.

Following step by step the code the value allways return a valid key.

Tks for your help.

2
  • Do you have a display for the id on your view? Something like @Html.HiddenFor(m=>m.IntIdCondicion) with Razor. edit: I should point out the reason behind this question is that what is available to the post action is only what comes from the front end, not what was returned in the earlier get method. Mar 26, 2012 at 21:17
  • No I don't have it.. the view was generated automatically Mar 26, 2012 at 21:19

1 Answer 1

1

By default EF expects that all integer primary keys are generated in a database. So modify your mapping and tell EF that your primary key is not autogenerated:

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int IntIdCondicion { get; set; }

If you are using EDMX you must configure StoreGeneratedPattern to None in IntIdCondicion properties.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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