简体   繁体   English

如何从Entity Framework更新主键?

[英]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.

相关问题 如何更新实体框架中的主键值? - How to update primary key value in entity framework? VS实体框架中的Oracle实体不会更新代码中的主键 - Oracle entity in VS entity framework doesnt update the primary key in code 实体框架4:如何找到主键? - Entity Framework 4: How to find the primary key? Entity Framework Core 使用 CurrentValues.SetValues 从其他实体更新实体属性,由于实体上的主键而失败 - Entity Framework Core using CurrentValues.SetValues to update entity properties from other entity failing due to primary key on entity 使用在多个列上具有主键的实体框架更新数据库 - Update Database using Entity Framework having primary key on multiple Columns 实体框架核心读取和更新多行-复合主键 - Entity Framework Core Read & Update Multiple rows - Composite Primary Key 如何将第一个表的主键值更新为第二个表的外键(实体框架代码第一个模型)? - How to update primary key values of first table into foreign keys in the second table (Entity framework code first model)? 如何使用 Entity Framework Core 从数据库表中确定通用实体的下一个主键? - How to determine the next primary key from a database table for a generic entity using Entity Framework Core? 如何在 C# 的外键中使用 Entity Framework 的复合主键 - How to use a composite primary key with Entity Framework from a foreign key in C# 使用Entity Framework 6创建主键 - Create primary key with Entity Framework 6
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM