2011-10-15 175 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 
}