2011-01-12 89 views
3

在數據庫中的 '類別' 表中這樣定義:實體框架IDENTITY_INSERT

CategoryID - PK ,identity specification ON (only this column has identity) 
Description 
Title 

我要插入新的數據:

Category cat = new Category 
{ 
    Description = "xxx", 
    Title = "yyy", 
}; 
if (cat.EntityState == EntityState.Detached) 
{ 
    Articlerctx.AddToCategories(cat); 
} 
return Articlerctx.SaveChanges(); 

我得到錯誤:

Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF.

但我不插入CategoryID!我希望它獲得自動價值!

+0

謝謝,問題出現在模型更新中!寫它作爲答案,我會接受它:) – asker 2011-01-12 16:20:30

+0

好,完成 - 使我的意見成爲一個答案 - 謝謝! – 2011-01-12 21:30:49

回答

4

您的場景在我的情況下工作得很好 - 使用EF4。

檢查以下各項:

  • ,您更改了數據庫模式,因爲你第一次創建你的實體模型,如果是這樣,你真的更新你的實體模型?

  • 是你的cat.EntityState真的是detached在那個時間點?在我的情況下,當使用EF4與ObjectContext時,它是Added。在這種情況下,您不會將新的Cat對象添加到類別集合中。

5

你的映射是錯誤的。該StoreGeneratedPatternCategoryID應該設置爲Identity,但你必須把它設置爲None。修復。