Juan Pablo Gomez
Juan Pablo Gomez

Reputation: 5524

Entity Framework Id Value assign:

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.

Upvotes: 0

Views: 684

Answers (1)

Ladislav Mrnka
Ladislav Mrnka

Reputation: 364259

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.

Upvotes: 1

Related Questions