Errors:
SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF.
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.
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();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.