如何从Entity Framework更新主键? [英] How to update primary key from Entity Framework?

查看:1386
本文介绍了如何从Entity Framework更新主键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有表

 事件ID INT  - 不PK的关键,但与自动增量
作业ID - PK自动增量禁用
用户ID INT - PK自动增量禁用

要更新作业ID我以下内容:

  VAR itemforupdate = context.table.where(N => n.eventid == someparameter).FirstorDefault()

我正确地从数据库中获得的项目,但分配时:

  itemforupdate.jobID = 5; 
context.SaveChanges();`

context.SaveChanges ()我得到的错误:




属性作业ID是对象的关键信息和$部分b $ b不能被修改




如何从实体框架更新作业ID来解决这个问题?


< DIV CLASS =h2_lin>解决方案

更新主键列是不符合的EntityFramework一个很好的做法。它混淆了EF,因为它改变了对象的身份,使保持在内存中的副本和数据在数据库副本同步很成问题。因此,它是不允许的。



只是不更新​​主键。相反,删除一行,并插入一个新的。



另外,您可以使用存储过程或其他查询直接更新的主键。


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:

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:

The property 'jobID' is part of the object's key information and cannot be modified

How to update jobID from Entity Framework to solve this problem?

解决方案

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆