[英]Cannot insert explicit value for identity insert ID manually entity when IDENTITY_INSERT is set to OFF
I have a table Worker
: 我有一个餐桌
Worker
:
public class Worker
{
public int ID { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Fathername { get; set; }
public string email { get; set; }
public string Company_name { get; set; }
}
I try to add a new worker: 我尝试添加新工人:
new Worker { Firstname = "John", Lastname = "Rambo", Fathername = "First_Blood", email = "Rocky@hh.ru", Company_name = "Survive" },
And I get error in application insights from last debug 我从上次调试中获得了应用程序见解中的错误
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries.
Microsoft.EntityFrameworkCore.DbUpdateException:更新条目时发生错误。 See the inner exception for details.
有关详细信息,请参见内部异常。
System.Data.SqlClient.SqlException: Cannot insert explicit value for identity column in table 'Worker' when IDENTITY_INSERT is set to OFF.
System.Data.SqlClient.SqlException:当IDENTITY_INSERT设置为OFF时,无法为表'Worker'中的标识列插入显式值。
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1
在System.Data.SqlClient.SqlConnection.OnError(SqlException异常,布尔值breakConnection,动作1
Of course I can remove ID and it added automatically. 当然,我可以删除ID并自动添加它。 But I want to add it manually of if it is nulled then generate automatically.
但是我想手动添加它是否为空然后自动生成。
Firstly, your ID column will never be null as you are using the int type and not the nullable int type. 首先,您的ID列永远不会为null,因为您使用的是int类型而不是可为null的int类型。
You can make your int type nullable by changing public int ID { get; set; }
您可以通过更改
public int ID { get; set; }
public int ID { get; set; }
public int ID { get; set; }
to public int? ID { get; set; }
public int ID { get; set; }
public int? ID { get; set; }
public int? ID { get; set; }
The reason you are receiving this error is because IDENTITY_INSERT
is set to off on your database. 您收到此错误的原因是因为
IDENTITY_INSERT
在您的数据库上设置为关闭。
If you apply the following attribute/convention to the property in your class and update the changes to the database you should find you are allowed to insert into the identity column. 如果将以下属性/惯例应用于类中的属性,并更新对数据库的更改,则应该允许您将其插入“标识”列。
public class Worker
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ID { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public string Fathername { get; set; }
public string email { get; set; }
public string Company_name { get; set; }
}
Alternatively, you can use the OnModelCreating overload as such; 另外,您可以使用OnModelCreating重载。
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Worker>().Property(x => x.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.None);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.