2011-10-15 47 views
0

需要我的插入代码帮助。我收到一个错误无法插入实体框架

“对象引用未设置为对象的实例”。

我对实体框架相当陌生。希望你们能帮助我。

这是代码:

protected void SaveButton_Click(object sender, EventArgs e) 
{ 
    var context = new MHC_CoopEntities(); 

    InventList product = new InventList 
         { 
          InventCategory = { CategoryID = 2 }, 
          ItemName = "Del Monte Fit & Right Pineapple 330ml", 
          UnitQty = 48, 
          UnitPrice = (decimal) 20.85 
         }; 

    context.AddToInventLists(product); 
    context.SaveChanges(); 
} 

堆栈跟踪:
在Coop_WebApp._Default.SaveButton_Click(对象 发件人,EventArgs e)在E:\其它\ Wabby KO \实体框架 4.0 \ EF_Soln \ Coop_WebApp \ Default.aspx.cs:线37
在System.Web.UI.WebControls.Button.OnClick(EventArgs的)
在System.Web.UI.WebControls.Button.RaisePostBackEvent(字符串 eventArgument)
在System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(字符串 eventArgument)
在System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,字符串eventArgument)
在System.Web.UI.Page.RaisePostBackEvent(NameValueCollection中POSTDATA)
在System.Web.UI.Page.ProcessRequestMain(布尔 includeStagesBeforeAsyncPoint,布尔includeStagesAfterAsyncPoint)

+0

你能发布完整的异常消息+堆栈跟踪吗? – ysrb

+0

问题现在已更新。 – Musikero31

+1

你可以尝试设置product.CategoryID = 2; ? – ysrb

回答

1

我假定product.InventCategory是具有类型的属性类别。当你做InventCategory = { CategoryID = 2 }时,它只设置CategoryID属性。但是,它需要这个对象。这就是为什么你需要从上下文中获取Category对象并使用它来设置InventCategory属性。希望这是有道理的。

0

您必须创建一个带有给定CategoryIDCategory实例,然后将其附加到上下文。附加是必须的,否则EF会在数据库中创建一个新的Category对象,而不是仅将relatonship设置为现有的类别2.您还应该确保正确地处理创建的上下文以释放数据库连接 - 例如通过包装代码变成using块:

protected void SaveButton_Click(object sender, EventArgs e) 
{ 
    using (var context = new MHC_CoopEntities()) 
    { 
     var category = new Category { CategoryID = 2 }; 
     context.Categories.Attach(category); 

     InventList product = new InventList 
        { 
         InventCategory = category, 
         ItemName = "Del Monte Fit & Right Pineapple 330ml", 
         UnitQty = 48, 
         UnitPrice = (decimal) 20.85 
        }; 

     context.AddToInventLists(product); 
     context.SaveChanges(); 
    } // <- context gets disposed here at the end of the using block 
}