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

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

问题描述

我想从实体框架内更新复合主键的一个值,我收到此错误:该物业客户ID是对象的关键信息的一部分,并不能修改

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. "

下面是我的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!

推荐答案

您不能有很好的理由。见KM意见。

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.

和登录时更改CustomerType和客户ID到你所需要的。

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天全站免登陆