![](/img/trans.png)
[英]SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF
[英]SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF
錯誤:
SqlException:當IDENTITY_INSERT設置為OFF時,無法為表'Recipe'中的Identity列插入顯式值。
Program.cs
class Program
{
static void Main(string[] args)
{
using (RecipesEntities context = new RecipesEntities())
{
//context.Categories.Add(new Category { Name = "Breakfast" });
//context.Categories.Add(new Category { Name = "Lunch" });
//new receipe and assign it to these two new categories
// 1. Using Id properties
//Category category = context.Categories.FirstOrDefault(c => c.Name == "Breakfast");
//context.Recipes.Add(new Recipe { Name = "Cereal", CategoryId = category.Id });
// 2. Recipe.Category navigation property
Category category = context.Categories.FirstOrDefault(c => c.Name == "Lunch");
context.Recipes.Add(new Recipe { Name = "Pizza", Category = category });
context.SaveChanges();
}
}
}
我的數據庫設計
食譜數據這里應該是披薩。
我知道這有點舊,但是對於任何在這里看到此問題的人來說,都是指向Microsoft文檔的鏈接,其中解釋了如何修復它。
對於您的問題,您可以嘗試通過打開和關閉“身份插入”來保存您的保存文件來修復它。
context.Database.OpenConnection();
try
{
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Recipe ON");
context.SaveChanges();
context.Database.ExecuteSqlCommand("SET IDENTITY_INSERT dbo.Recipe OFF");
}
finally
{
context.Database.CloseConnection();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.