簡體   English   中英

SqlException:當IDENTITY_INSERT設置為OFF時,無法為表'Recipe'中的Identity列插入顯式值

[英]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

  1. 我添加了兩個類別“早餐”和“午餐”。
  2. 可以制作一個屬於“ BreakFast”的新食譜
  3. 如果我嘗試添加新食譜,則會收到錯誤消息。
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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM