简体   繁体   English

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

[英]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我正在尝试将一些数据保存到我的 MenuItems 表中,但我被错误阻止了

SqlException: Cannot insert explicit value for identity column in table 'MenuCategories' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“MenuCategories”中插入标识列的显式值

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.我只是想使用我拥有的类别 id 设置外键,我不太确定为什么会收到上述错误。

This is my MenuItem model:这是我的菜单项MenuItem

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:这是我的菜单类别MenuCategory

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.我正在尝试为其分配现有类别的 id,我不希望它创建一个新类别。

Based on your comments of you wanting to use an existing Id to not add a new category, then what you are doing for your save is a little wrong _Context.Add(menuItem);根据您希望使用现有 Id 不添加新类别的评论,那么您为保存所做的操作有点错误_Context.Add(menuItem); will cause a database INSERT to fire - this is because the .Add() marks all of the entities as new entities to be saved to the context, yet you arent wanting that - what you should do is something along the lines of Add the menuItem - Query the Database to get the MenuCategory that you want to have attached to it - and then set that on the menuItem and then save.将导致数据库INSERT触发-这是因为.Add()将所有实体标记为要保存到上下文中的新实体,但您不希望这样做-您应该做的是类似于 Add the menuItem - 查询数据库以获取您想要附加到它的MenuCategory - 然后在menuItem上设置它,然后保存。

I have to assume that your DbContext class is like this:我必须假设您的DbContext class 是这样的:

public class Context: DbContext
{
    public Context(DbContextOptions<MenuContext> options)
        : base(options)
    { }

    public DbSet<MenuCategory> MenuCategories{ get; set; }
    public DbSet<MenuItem> MenuItems { get; set; }
}

So your controller can be coded this way:所以你的 controller 可以这样编码:

public async Task<IActionResult> Create(MenuItemViewModel model)
{
    if (ModelState.IsValid)
    {
        var menuItem = new MenuItem 
        {
            Name = model.Name,
            ...
        };

        var menuCategory = _Context.MenuCategories.Find(model.MenuCategory.MenuCategoryId);
        menuItem.MenuCategory = menuCategory;
        _Context.MenuItems.Add(menuItem);
        await _Context.SaveChangesAsync();
        return RedirectToAction(nameof(Index), new { id = menuItem.MenuCategory.MenuCategoryId });
    }
    return View(menuItem);
}

From what I can tell, you are assuming that if you tell your View that your MenuCategory has a selected id, your view will populate the MenuCategory .据我所知,你假设如果你告诉你的视图你的MenuCategory有一个选定的 id,你的视图将填充MenuCategory It does not work that way.它不是那样工作的。 The view does not have a way of knowing what your MenuCategory is.该视图无法知道您的MenuCategory是什么。 You need to populate the values with your DbContext , which happens in your controller .您需要使用您的DbContext填充值,这发生在您的controller中。

Also, it would be best if you separate your entities from your view models .此外,最好将实体视图模型分开。 It is so much easier if your classes have their own simple responsibility: your entities will represent a logical record in your database, and your view model will represent the data that comes from and goes to your controllers.如果您的类有自己的简单职责,那就容易多了:您的实体将代表数据库中的逻辑记录,而您的视图 model 将代表来自和去往您的控制器的数据。

On your SQL table definition you likely have something like IDENTITY(1,1) on the MenuItemId field.在您的 SQL 表定义中,您可能在 MenuItemId 字段上有类似 IDENTITY(1,1) 的内容。 This will generate the next consecutive Id for you, so you shouldn't be passing one in.这将为您生成下一个连续的 Id,因此您不应该传入一个。

You can also get this error if you've 'implicitly' added an entity to the database, saved it and then try to manually add it.如果您已“隐式”将实体添加到数据库、保存它然后尝试手动添加它,您也可能会收到此错误。

Clearly the following is HORRIBLE code and would make no sense to write this.很明显,下面是可怕的代码,写这个没有意义。 However it's possible to do this accidentally with a more complicated situation.但是,在更复杂的情况下可能会意外地做到这一点。

var category = new MenuCategoryViewModel() { ... };

// assign category to menu item    
var model = new MenuItemViewModel() 
            {
                MenuCategory = category 
            };  

db.Add(model);
db.SaveChanges();

// 'category' object has an ID because we saved it
// even though it was never explicitly added to the context

// add the category to the context 
db.Add(category);
db.SaveChanges();  // fails with IDENTITY error

If you are adding an entity without explicitly adding it to the context you mustn't add it later after it already has been assigned a key.如果您要添加一个实体而没有将其显式添加到上下文中,则您不能在已为其分配键之后再添加它。

In my case, this exception was thrown because the software had an entity with auto generated ID and I tried to insert a new record in database with an id generated by my code.在我的情况下,抛出这个异常是因为软件有一个具有自动生成 ID 的实体,我试图在数据库中插入一条新记录,其 ID 由我的代码生成。 The solution was clear and simple: remove the ID set in my code.解决方案简单明了:删除我的代码中设置的 ID。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法为表 [表名] 中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table [Table name] when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;Recipe&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Recipe' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;AspNetUsers&#39;中的Identity列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'AspNetUsers' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表 'Ogretmenler' 中为标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table 'Ogretmenler' when IDENTITY_INSERT is set to OFF SqlException:当IDENTITY_INSERT设置为OFF时,无法为表&#39;&#39;中的标识列插入显式值 - SqlException: Cannot insert explicit value for identity column in table '' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF 时,无法在表“任务”中插入标识列的显式值 - SqlException: Cannot insert explicit value for identity column in table 'Tasks' when IDENTITY_INSERT is set to OFF SqlException:当 IDENTITY_INSERT 设置为 OFF ASP.NET Core 2.1 时,无法在表“类别”中插入标识列的显式值 - SqlException: Cannot insert explicit value for identity column in table 'Categories' when IDENTITY_INSERT is set to OFF ASP.NET Core 2.1 IDENTITY_INSERT设置为OFF时,EF无法为表“ PATIENT DONOR”中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'PATIENT DONOR' when IDENTITY_INSERT is set to OFF IDENTITY_INSERT设置为OFF时,EF无法为表&#39;X&#39;中的标识列插入显式值 - EF Cannot insert explicit value for identity column in table 'X' when IDENTITY_INSERT is set to OFF EF Core:当 IDENTITY_INSERT 在一对多上设置为 OFF 时,无法在表中插入标识列的显式值 - EF Core: Cannot insert explicit value for identity column in table when IDENTITY_INSERT is set to OFF on one to many
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM