LINQ 对组合键的可悲处理
我有一个表,它有一个复合键,由两个 int 字段和一个 varchar(50) 字段组成。我将复合键作为我的主键,但我通常不这样做。是的,是的,是的,我非常熟悉逻辑键与代理键的辩论,但自从我采用逻辑键方法以来,我在制作表格的那天一定使用了一些重毒(不是真的)使用代理人(我几乎总是这样做)。
我的问题:LINQ 不允许我对作为组合键一部分的 varchar(50) 列进行更新。它抛出异常“属性‘Value’是对象关键信息的一部分,无法修改。” “值”是字段的名称(请不要教我使用保留字作为列名称......就像我已经说过的那样,我那天正在服用严重的药物)。
那么,除了进退两难之外,这对我来说又意味着什么呢?所讨论的表实际上确实有一个唯一的标识列(即使它不是主键),并且该列正在另一个表的外键中使用。所以,呃,我不能很容易地做一些黑客操作,比如删除有问题的记录并重新添加它,因为这将迫使我跟踪其他表中的 fk,然后也重新添加它们。真是一场噩梦……
有人知道一种简单的方法来解决这个问题,而不强迫我对表结构进行大量更改吗?
I have a table that has a composite key that consists of two int fields and one varchar(50) field. I made the composite key my primary key, which I don't usually do. Yes, yes, yes, I'm more than familiar with the logical key vs. surrogate key debate, but I must have done some heavy drugs (not really) the day that I made the table since I went with the logical key approach instead of using a surrogate (which I almost always do).
My problem: LINQ won't let me do an update on the varchar(50) column that is part of the composite key. It throws the exception "The property 'Value' is part of the object's key information and cannot be modified." 'Value' is the name of the field (and please don't lecture me on using reserved words for column names... like I already said, I was on serious drugs the day of).
So where does this leave me, besides between a rock and a hard place? The table in question actually does have a unique, identity column (even though it's not the primary key), and this column is being used in a foreign key to another table. So, duh, I can't very easily do some hack like delete the record in question and re-add it, because that would force me to keep track of the fk's in other tables and then re-add them as well. What a nightmare...
Anyone know an easy way to get around this issue without forcing me to make extensive changes to my table structure?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果该表上已有唯一的 IDENTITY 列,那么它应该是您的主键。主键应该始终仅在表中最小大小的候选(唯一)键之间进行选择,并且几乎始终应该是不可变的。
您甚至不必将 IDENTITY 列设置为数据库上的主键,只需将其设置为 Linq to SQL 模型中的键列,一切都会正常工作。
If you already have a unique IDENTITY column on that table, then it should be your primary key. Primary keys should always be a choice only between the minimum sized candidate (unique) keys in a table, and should almost always be immutable.
You don't even have to make your IDENTITY column the PRIMARY KEY on the database, you can just make it the key column in your Linq to SQL model, and everything should work just fine.
如果您尝试更新形成复合键的列,我会说您的表无论如何都已损坏,而且损坏的不是 LINQ。告诉 LINQ 您的身份列是您的密钥,或者使用 SPROC 进行所需的更新。
If you're trying to update a column that forms a composite key, I'd say your table is broken anyway, and it's not LINQ that is broken. Tell LINQ that your identity column is your key, or use a SPROC to do the update that is required.