如何更新aprimary键字段与LINQ to SQL的? [英] How to update a aprimary key field with linq to SQL?

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

问题描述

我有以下字段tbl_names:

I have tbl_names with following fields:

Id  int
Name nvarchar(10)
family nvarchar(20)


Id    Name    Family
 1     John     Smith

和假设编号名称是主键合(复合主键)。
我想根据编号字段。

and suppose Id and name are primary key together(compound primary key). and I want to update name field according to the value of Id field.

DataclassesContext dac=new DataClassesContext();
var query=from record in Dac.tbl_name where record.id=1 select record;
query.name="Raymond";
Dac.Submitchanges();

但我遇到以下错误:

but I encounter following error:

Value of member 'co_Workshop' of an object of type 'Tbl_Workshop' changed.
A member defining the identity of the object cannot be changed.
Consider adding a new object with new identity and deleting the existing one instead.

是因为的名称字段是主键?使用LINQ为什么我不能更新主键字段?

Is it because of name field is primary key? why can't I update a primary key field using linq?

推荐答案

我不知道,你应该找到解决的办法。我想不通为什么它会在PK更改值是一个好主意。一个PK的整个性质是,它是该行的一个稳定的标识符

I am not sure that you should find a way around this. I cannot imagine why it would be a good idea to change a value in a PK. The entire nature of a PK is that it is a stable identifier of the row.

在你的情况,你应该删除并重新创建PK是只是ID区域,然后如果你需要改进的查询筛选的名,那么只是在名称字段添加索引的性能。您只使用标识字段来查找记录的事实支持这种想法。

In your case, you should drop and recreate the PK to be just the "Id" field and then if you need to improve performance on queries filtering on "name" then just add an Index on the "name" field. The fact that you only use the "Id" field to find the record supports this idea.

编辑:
我回答之前有意见的问题。现在,我看到关于OP评论这是一个旧的数据库和不能改变它的结构,我会说,如果没有指向该FKS PK的话,这应该是一个相当直接的变化(以下降,刚好在ID区域重建的PK正如我上面提到)。如果有的FKS指向它,然后一个选项(虽然不是一个很好的选择,它可能无法在所有RDBMS的工作)是:

I answered before there were comments to the Question. Now that I see the comment from the OP about "it is an old database and can't change it's structure", I would say that if there are no FKs pointing to this PK then this should be a fairly straight-forward change (to drop and recreate the PK with just the "Id" field as I mentioned above). If there are FKs pointing to it then an option (though not a great option and it might not work on all RDBMS's) is to:


  1. 挂断了FKS

  2. 挂断的PK

  3. 在只是ID区域创建新的PK

  4. 创建的ID和名称
  5. 唯一索引
  6. 重新创建FK的指向唯一索引

这将工作Microsoft SQL Server上并不亚于我不喜欢一个FK指向唯一索引的想法,应该允许对你现在的以及的LINQ只会看到相同的结构在ID的单场PK,并允许进行更新。

This will work on Microsoft SQL Server and as much as I dislike the idea of a FK pointing to a UNIQUE INDEX, it should allow for the same structure that you have now plus LINQ will just see the single field PK on "Id" and allow for the update.

这篇关于如何更新aprimary键字段与LINQ to SQL的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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