5

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:

[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? 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. 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. 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.

Christof
  • 3,777
  • 4
  • 37
  • 49
  • With a `[Table]` attribute, it should be LINQ-to-SQL, right? – xanatos Mar 15 '15 at 18:09
  • The code is correct, if I remember correctly. Are both of them manually set by the program, or is one an autoincrement? – xanatos Mar 15 '15 at 18:14
  • Both are foreign keys and auto-incremented in their own table. The values I'm writing to the PartToPart table are done manually by the program. – Christof Mar 15 '15 at 18:15
  • Your error is probably somewhere else... Perhaps you are trying to insert the same record twice or something similar. – xanatos Mar 15 '15 at 18:17
  • What data are you trying to insert? I usually use [Key] attribute (like described here https://msdn.microsoft.com/en-us/data/jj591583.aspx#Composite), but I think IsPrimaryKey = true should do the same thing. Looks ok. – m0n0ph0n Mar 15 '15 at 18:31
  • Just two integers, or what did you mean? I saw the `[Key]` example, but VS says it's invalid when I try that? – Christof Mar 15 '15 at 18:52
  • @xanatos you were right, classical PEBCAK problem :). My code was being executed twice -.- If you care to add your comment as an answer, I'll be happy to accept it. – Christof Mar 15 '15 at 18:54

1 Answers1

4

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. 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)

xanatos
  • 109,618
  • 12
  • 197
  • 280