【问题标题】:SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFFSqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Recipe”中插入标识列的显式值
【发布时间】:2018-12-30 03:57:22
【问题描述】:

错误:

SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“Recipe”中插入标识列的显式值。

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();
        }
    }
}

我的数据库设计

Diagram

Category Data

Category Design

Recipe Data这里应该是披萨。

Recipe Design

【问题讨论】:

  • 你能分享你的食谱课吗?
  • public int Id { get;放; } 公共字符串名称 { 获取;放; } public Nullable CategoryId { get;放; } 公共虚拟类别类别 { 获取;放; }
  • 您可以尝试将 [Key]-annotation 添加到您的 Id 并检查 this answer 是否有帮助。
  • 我得到同样的错误:(

标签: c# entity-framework ado.net


【解决方案1】:

我知道这有点老了,但是对于看到这个的任何人here is a link to the Microsoft Docs explaining how to fix it.

对于您的问题,您可以尝试通过打开和关闭身份插入来围绕您的保存来解决它。

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();
}

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 2019-11-11
    • 1970-01-01
    • 2020-03-09
    • 2016-05-13
    • 2016-08-18
    • 2019-03-10
    相关资源
    最近更新 更多