使用实体框架更新主键值 [英] Update primary key value using entity framework

查看:102
本文介绍了使用实体框架更新主键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从实体框架中更新复合主键的一个值,并且我收到此错误:属性CustomerID是对象的关键信息的一部分,无法修改。



这是我的代码:

  Dim customer As Customer =(From c在db.Customer中c.CustomerID =xxxAndAlso c.SiteKey = siteKey).FirstOrDefault 
customer.CustomerID =fasdfasdf
db.SaveChanges()

看起来太简单了是否真的不能在实体框架内更新主键?我找不到有关该主题的任何文档。谢谢!

解决方案

你不能,因为很好的理由。请参阅KM的意见。



我所说的一件事可能是有两个表,一个是匿名数据,一个在登录后存储真正的用户数据。 p>

或者你的可能(未经测试或曾经做过我的)有这种表格布局:

  ---客户---- 
自动编号PK< - 这链接到数据库中的所有其他表,不会更改。
CustomerID< - 这可以改变。
CustomerType< - 匿名或登录

当他们登录时,您更改CustomerType和CustomerID,以满足您的需要。



所以您的查询可能如下所示:

 code> Dim customer As Customer =(From c In db.Customer _ 
Where c.CustomerID = {Some temp ID} _
AndAlso c。CustomerType =Anonymous)。FirstOrDefault
//用户登录后
customer.CustomerID = {在此创建新的用户ID}
customer.CustomerType =LoggedIn{或什么}
db.SaveChanges()

请注意,自动编号主键永不更改。这就是说,与客户表关系中的任何表格仍然可以工作,而不必在主键上进行级联更新(这就像用铅笔刺伤你的眼睛)。 em>


I'm trying to update one value of a compound primary key from within the entity framework and I'm getting this error: "The property 'CustomerID' is part of the object's key information and cannot be modified. "

Here is my code:

Dim customer As Customer = (From c In db.Customer Where c.CustomerID = "xxx" AndAlso c.SiteKey = siteKey).FirstOrDefault
customer.CustomerID = "fasdfasdf"
db.SaveChanges()

It seems too simple. Is it true you can't update a primary key within the entity framework? I can't find any documentation on the topic. Thanks!

解决方案

You can't and for good reason. See KM comments.

One thing I say you could do is have two tables one with anonymous data and one that stores the the real user data after they log in.

Or your could (not tested or ever done by me) is have this kind of table layout:

---Customers----
AutoNumber PK <- This links to all other tables in your database, and does NOT change.
CustomerID  <- This can change.
CustomerType <- Anonymous or logged in.  

And when they log in you change the CustomerType and CustomerID to what you need.

So your query could look like this:

Dim customer As Customer = (From c In db.Customer _
                            Where c.CustomerID = {Some temp ID} _
                            AndAlso c. CustomerType = "Anonymous").FirstOrDefault
// After user logs in.
customer.CustomerID = {Make a new user ID here}
customer.CustomerType = "LoggedIn" {or what ever}
db.SaveChanges()

Note that the autonumber primary key never changes. This is so that any tables that you have in a relationship with the Customers table still work and don't have to do cascading updates on the primary key (which is like stabbing yourself in the eye with a pencil).

这篇关于使用实体框架更新主键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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