简体   繁体   中英

Entity Framework:Foreign Key as part of Composite key

We have requirements where we are required to use a foreign key as a part of Composite key in another table. eg

Public Primary_Class{
    public int pkey{get; set;}
    public string Misc{get; set;}
}


Public dependent_Class{
    *public int dkey {get; set;} /*Column 1 of Primary key*/
    public int pkey{get; set;}  /*Cloumn 2 of PK as well as FK to Primay_Class*/

    pubic string data{get; set;}
}

Could please help me achieve this in Entity Framework 6.0

It seems that you ever tried but still I'm answering.

In Entity Framework you can achieve this by using Entity Framework Code First Data Annotations .

Here is complete solution:

public class Primary_Class
{
    [Key]
    public int pkey { get; set; }
    public string Misc { get; set; }
}
public class dependent_Class
{
    [Key]
    public int dkey { get; set; } //*column 1 of Primary key*/

    [ForeignKey("Primary_Class")]
    [Column(Order = 1)]
    public int pkey { get; set; }  //*Cloumn 2 of PK as well as FK to Primay_Class*
    public string data{get; set;}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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