2012-03-26 71 views
0

我有一个分贝第一个模型定义为一个实体:实体框架ID值分配:

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; } 
} 

和自动生成的控制器,该控制器具有此创建操作:

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); 
} 

这个实体有一个Id列在HttPost中手动分配(创建操作)。 问题是,一个错误使我无法在IntIdCondicion列中插入NULL值。

按照步骤代码值allways返回一个有效的关键。

Tks为您提供帮助。

+0

您是否在视图上显示了ID?像使用Razor的'@ Html.HiddenFor(m => m.IntIdCondicion)'。编辑:我应该指出这个问题背后的原因是,后期操作可用的内容仅仅来自前端,而不是早期get方法返回的内容。 – 2012-03-26 21:17:53

+0

不,我没有它..视图自动生成 – 2012-03-26 21:19:07

回答

1

默认情况下,EF期望在数据库中生成所有整型主键。因此,修改映射,并告诉你的主键是不是EF自动生成:如果您使用的EDMX

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

必须在IntIdCondicion性能配置StoreGeneratedPatternNone

+0

非常感谢您的帮助。 – 2012-03-26 21:32:57