编辑主键 [英] Edit Primary Key

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

问题描述

如果表仅包含主键字段,是否可以在MVC3中编辑主键.例如,我有一个控制台表,并且在其中有控制台名称作为主键,我希望能够对其进行编辑,更改并保存编辑后的值.

Is there a way of editing the primary key in MVC3 if the table only contains a primary key field. For example I have a console table and within it i have the console name as the Primary key and I want to be able to edit it and change it and save the edited value.

如果您需要更多信息,请告诉我.

If there is any more info you require please let me know.

推荐答案

作为一般规则,切勿编辑主键.SQL Server中的主键通常在其上具有聚集的唯一索引,因此编辑主键意味着您可能必须重建索引(可能不是每次都重建,但取决于倾斜).

As a general rule, you should never edit primary keys. The primary key in SQL Server typically has a clustered unique index on it, so editing the primary key means you potentially have to rebuild your indexes (maybe not every time, but depending on the skew).

相反,我将创建一个伪造的主键(例如SQL Server中的IDENTITY列),并将UNIQUE约束放在Name列上.如果表变大,则在int列上检索项目也将比在varchar()列上检索更快.

Instead I would create a fake primary key, such as an IDENTITY column in SQL Server, and put a UNIQUE constraint on the Name column. If your table grows large, retrieving items on an int column will also be faster than retrieving on a varchar() column.

更新:由于有人告诉我我没有回答问题(即使这是公认的答案),因此可以更改SQL Server中的主键值.但这从技术上讲不是编辑操作,因为参照完整性可能会阻止真正的编辑(我还没有尝试过,请随时进行自己的实验!)

Update: Since I was told I didn't answer the question (even though this is the accepted answer), it is possible to change the primary key values in SQL Server. But it is not technically an edit operation, since referential integrity may prevent a true edit (I haven't tried, so feel free to conduct your own experiment!)

该操作将如下所示:

  1. 使用新的PK值在主表中添加新行
  2. 运行更新操作,将所有FK值更改为新的PK值
  3. 删除旧的PK行

我也会在事务中运行所有这些.但我会再次声明,我不建议您采用这种方法.

I'd run all that in a transaction, too. But I will state again for the record, I do not recommend taking this approach.

这篇关于编辑主键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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