简体   繁体   English

Linq 2 SQL:复合主键

[英]Linq 2 SQL: composite primary key

I have a linking table with two foreign keys. 我有一个带有两个外键的链接表。 Together, they are the primary key for the table. 它们是桌子的主要关键。 I am trying to map this in Linq: 我想在Linq中映射这个:

[Table(Name = "PartToPart")]
public class PartToPart
{
    [Column(Name = "PartID", IsPrimaryKey = true )]
    public int PartID { get; set; }

    [Column(Name = "ParentPartID", IsPrimaryKey = true)]
    public int ParentPartID { get; set; }
}

I'm assuming this is wrong and making Linq assume both columns are primary key on their own? 我假设这是错误的,并使Linq假设两列都是他们自己的主键? If I try saving new entries to this table, I get a constraint violation error: 如果我尝试将新条目保存到此表,我会收到约束违规错误:

Violation of primary key constraint ... Cannot insert duplicate key in object dbo.PartToPart. 违反主键约束...无法在对象dbo.PartToPart中插入重复键。 The duplicate key value is ... 重复的键值是......

I tried inserting the keys manually via an INSERT query and that works just fine, so I'm assuming my table is setup correctly. 我尝试通过INSERT查询手动插入键,并且工作正常,所以我假设我的表设置正确。 What's strange is that the insert works regardless of the error message. 奇怪的是,无论错误消息如何,插入都有效。

I checked the docs and to me it sounds like it should work the way I have it: 我检查了文档 ,对我来说听起来应该像我一样工作:

If you designate more than one member of the class by using this property, the key is said to be a composite of the associated columns. 如果使用此属性指定类的多个成员,则该键称为关联列的组合。

Any help on this? 对此有何帮助? Thanks. 谢谢。

Your class definition is correct. 你的班级定义是正确的。 You write entities with composite keys exactly as you have written. 您可以使用与编写完全相同的复合键来编写实体。 Note that as written, the keys must be set by the C# code, and they aren't auto-incrementing fields. 请注意,如上所述,密钥必须由C#代码设置,并且它们不是自动递增字段。 You told me this is exact, so this isn't the problem. 你告诉我这是确切的,所以这不是问题所在。

Given the error, I'll say you are trying to insert twice the same record (and/or inserting twice an "empty" record, that then has the PartID and the ParentPartID set at 0 by the .NET) 鉴于错误,我会说你试图插入两次相同的记录(和/或插入两次“空”记录,然后由.NET将PartIDParentPartID设置为0)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM