Christof
Christof

Reputation: 3927

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:

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

Upvotes: 5

Views: 5727

Answers (1)

xanatos
xanatos

Reputation: 111830

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)

Upvotes: 4

Related Questions