如何从Entity Framework更新主键? [英] How to update primary key from Entity Framework?
问题描述
我有表
eventid int -- not PK key but with autoincrement
jobid -- PK autoincrement disabled
userid int -- PK autoincrement disabled
要更新jobID,请执行以下操作:
To update jobID I do following:
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()
错误:
属性jobID是对象的关键信息的一部分,
无法修改
The property 'jobID' is part of the object's key information and cannot be modified
如何从Entity Framework更新jobID以解决这个问题?
How to update jobID from Entity Framework to solve this problem?
推荐答案
更新主键列不是EntityFramework的好习惯。它会混淆EF,因为它会更改对象的身份,并保持内存中的副本和数据库中的数据库副本同步非常有问题。所以这是不允许的。
Updating primary key columns is not a good practice with 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. 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.
这篇关于如何从Entity Framework更新主键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!