Fernando Tiberti
Fernando Tiberti

Reputation: 1322

Entity Framework, having a primary key that is a reference to an entity with composite primary key

So I have a class that has a composite primary key:

public class Field
{
    [Key, Column(Order=0)]
    [ForeignKey("Store")]
    public int StoreID { get; set; }
    public Store Store { get; set; }

    [Key, Column(Order = 1)]
    public int ID { get; set; }


    public List<Template> Templates { get; set; }
}

...and another one that references it

public class Mapping
{
    public Field Field { get; set; }

    [ForeignKey("Template")]
    public int TemplateID { get; set; }
    public Template Template { get; set; }
}

This works well except that Mapping is missing its primary key, because I don't know how to do it. What I want is the class Mapping to have a composite primary key formed by Field and Template. The difficulty lies for me in that the Field class also has a composite key.

Upvotes: 2

Views: 1398

Answers (1)

Slauma
Slauma

Reputation: 177153

You would need something like this:

public class Mapping
{
    [Key, ForeignKey("Field"), Column(Order=0)]
    public int StoreID { get; set; }

    [Key, ForeignKey("Field"), Column(Order=1)]
    public int ID { get; set; }

    [Key, ForeignKey("Template"), Column(Order=2)]
    public int TemplateID { get; set; }

    public Field Field { get; set; }
    public Template Template { get; set; }
}

For the ForeignKey attribute you can specify a composite key order like for the Key attribute. Alternatively you can also put the ForeignKey attribute on the navigation property and then specify the FK properties with comma separation:

public class Mapping
{
    [Key, Column(Order=0)]
    public int StoreID { get; set; }

    [Key, Column(Order=1)]
    public int ID { get; set; }

    [Key, Column(Order=2)]
    public int TemplateID { get; set; }

    [ForeignKey("StoreID, ID")]
    public Field Field { get; set; }

    [ForeignKey("TemplateID")]
    public Template Template { get; set; }
}

(Edit Duplicate Column attribute was wrong -> Corrected.)

Upvotes: 3

Related Questions