首页 > 解决方案 > EF Core SqlException: Cannot insert explicit value for identity column in table 'MenuCategories' when IDENTITY_INSERT is set to OFF

问题描述

I am trying to save some data into my MenuItems table but I'm prevented by the error

SqlException: Cannot insert explicit value for identity column in table 'MenuCategories' when IDENTITY_INSERT is set to OFF

I am just trying to set the foreign key using the category id I have, I am not quite sure why I am getting the above error.

This is my MenuItem model:

public class MenuItemViewModel
{
    [Key]
    [Column("MenuItem_Id")]
    public int MenuItemId { get; set; }

    [Required]
    public string Name { get; set; }

    [Required]
    public string Description { get; set; }

    [Required]
    public decimal Price { get; set; }

    [Required]
    [Column("MenuCategory_Id")]
    public MenuCategoryViewModel MenuCategory { get; set; }
}

This is my MenuCategory model:

public class MenuCategoryViewModel
{
    [Key]
    [Column("MenuCategory_Id")]
    public int MenuCategoryId { get; set; }

    [Required]
    public string Name { get; set; }
}

I'm trying to assign it the id of an existing category, I do not want it to create a new category.

标签: c#sqlentity-frameworkasp.net-core

解决方案


根据您希望使用现有 Id 不添加新类别的评论,那么您为保存所做的操作有点错误_Context.Add(menuItem);会导致数据库INSERT触发 - 这是因为将.Add()所有实体标记为新实体要保存到上下文中,但您不希望这样-您应该做的是类似于添加menuItem-查询数据库以获取MenuCategory要附加到它的内容-然后将其设置在menuItem然后保存.


推荐阅读