gpt4 book ai didi

asp.net - EF 代码第一个 : Cannot insert explicit value for identity column in table 'myTable' when IDENTITY_INSERT is set to OFF

转载 作者:行者123 更新时间:2023-12-02 10:26:00 32 4
gpt4 key购买 nike

将主键设置为数据库(SQL Server)中的身份

使用 EF 插入数据时出现错误

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

对于这个特定的实体,尽管我对其他实体使用相同的方法来插入数据并且没有出现错误。

   public class MyTable 
{
[Key/*,DatabaseGenerated(DatabaseGeneratedOption.Identity)*/]
public int ID{get;set;}
public string name {get;set;}
public string type {get;set;}
public string status {get;set;}
public int country {get;set;}
public DateTime start_date {get;set;}
public DateTime due_date {get;set;}
}`

查询

    MyTable check= new MyTable();
check.name = checkName;
check.type = "DB";
check.status = "New";
check.country = country;
check.start_date = DateTime.Now;
check.due_date = dueDate;
db.myTables.Add(check);
db.SaveChanges();

更新:

取消上面一行的注释后

(DatabaseGenerated(DatabaseGeneratedOption.Identity)) 

抛出异常

A dependent property in a ReferentialConstraint is mapped to a store-generated column. Column: 'ID'

最佳答案

试试这个:

[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

关于asp.net - EF 代码第一个 : Cannot insert explicit value for identity column in table 'myTable' when IDENTITY_INSERT is set to OFF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12811931/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com