Linq 2 SQL: 复合主键
Linq 2 SQL: composite primary key
我有一个带有两个外键的链接 table。它们一起是 table 的主键。我正在尝试在 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; }
}
我假设这是错误的,让 Linq 假设这两列都是它们自己的主键?如果我尝试将新条目保存到此 table,我会收到约束违规错误:
Violation of primary key constraint ... Cannot insert duplicate key in object dbo.PartToPart. The duplicate key value is ...
我尝试通过 INSERT 查询手动插入密钥并且效果很好,所以我假设我的 table 设置正确。奇怪的是,无论错误消息如何,插入都有效。
我检查了 the docs,对我来说它听起来应该像我拥有的那样工作:
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.
有什么帮助吗?
谢谢。
您的 class 定义是正确的。您可以完全按照您编写的方式使用复合键编写实体。请注意,如所写,键必须由 C# 代码设置,并且它们不是自动递增字段。你告诉我这是准确的,所以这不是问题所在。
鉴于错误,我会说您正在尝试插入两次相同的记录(and/or 插入两次 "empty" 记录,然后有 PartID
和 ParentPartID
由 .NET 设置为 0)
我有一个带有两个外键的链接 table。它们一起是 table 的主键。我正在尝试在 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; }
}
我假设这是错误的,让 Linq 假设这两列都是它们自己的主键?如果我尝试将新条目保存到此 table,我会收到约束违规错误:
Violation of primary key constraint ... Cannot insert duplicate key in object dbo.PartToPart. The duplicate key value is ...
我尝试通过 INSERT 查询手动插入密钥并且效果很好,所以我假设我的 table 设置正确。奇怪的是,无论错误消息如何,插入都有效。
我检查了 the docs,对我来说它听起来应该像我拥有的那样工作:
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.
有什么帮助吗? 谢谢。
您的 class 定义是正确的。您可以完全按照您编写的方式使用复合键编写实体。请注意,如所写,键必须由 C# 代码设置,并且它们不是自动递增字段。你告诉我这是准确的,所以这不是问题所在。
鉴于错误,我会说您正在尝试插入两次相同的记录(and/or 插入两次 "empty" 记录,然后有 PartID
和 ParentPartID
由 .NET 设置为 0)