[英]SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF
Errors: 错误:
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 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();
}
}
}
My database design 我的数据库设计
Recipe Data Here should be a pizza. 食谱数据这里应该是披萨。
I know this is a bit old, but for anyone who sees this here is a link to the Microsoft Docs explaining how to fix it. 我知道这有点旧,但是对于任何在这里看到此问题的人来说,都是指向Microsoft文档的链接,其中解释了如何修复它。
For your problem, you can try to fix it by surrounding your save with opening and closing of the Identity Insert. 对于您的问题,您可以尝试通过打开和关闭“身份插入”来保存您的保存文件来修复它。
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.