[英]How to update primary key from Entity Framework?
I have Table 我有桌子
eventid int -- not PK key but with autoincrement
jobid -- PK autoincrement disabled
userid int -- PK autoincrement disabled
To update jobID I do following: 要更新jobID,我会执行以下操作:
var itemforupdate = context.table.where(n=>n.eventid == someparameter).FirstorDefault()
I get the item from database correctly, but when assigning: 我正确地从数据库中获取项目,但在分配时:
itemforupdate.jobID = 5;
context.SaveChanges();
after context.SaveChanges()
I get the error: 在
context.SaveChanges()
我得到错误:
The property 'jobID' is part of the object's key information and cannot be modified
属性“jobID”是对象的关键信息的一部分,无法修改
How to update jobID from Entity Framework to solve this problem? 如何从Entity Framework更新jobID来解决这个问题?
Updating primary key columns is not a good practice with EntityFramework. 使用EntityFramework更新主键列不是一个好习惯。 It confuses EF because it changes the identity of the object, and makes keeping the in-memory copy and the in-database copy of the data in sync very problematic.
它会混淆EF,因为它会更改对象的身份,并使内存中的副本和数据库的数据库副本保持同步非常有问题。 So it's not allowed.
所以这是不允许的。
Just don't update primary keys. 只是不要更新主键。 Instead delete one row and insert a new one.
而是删除一行并插入一行。
Alternatively you can update the primary key directly with a stored procedure or other query. 或者,您可以使用存储过程或其他查询直接更新主键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.