简体   繁体   中英

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.

Program.cs

  1. I had add two category "Breakfast" and "Lunch".
  2. Could make a new Recipe there belongs to "BreakFast"
  3. If I try add a new recipe i get the error.
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

Diagram

Category Data

Category Design

Recipe Data Here should be a pizza.

Recipe Design

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM