locked
How to Link Foreign Key to a column other than primary key in EF6 Code First RRS feed

  • Question

  • Hi ,

    I have the following classes A and B .

    A has the property Id which is a PK,OrderId(Acts as foreign Key) and

    B has the columns Id,UserName,OrderID which should be related as a foreign key in Class A

    In the Code first approach ,I have defined those classes.However when I generate the migration and the SQL scripts using Update-Database -script ,class B is always referencing Id as the foreign key of class A

    Here is how my classes look like

    public class ClassA

    {

    [Key]

    public int Id{get;set;}

    public int OrderId{get;set;}

    }

    public class ClassB

    {

    [Key]

    public int Id{get;set;}

    public string userName {get;set;}

    [ForeignKey("A")]

    public int OrderId{get;set;}

    public virtual ClassA A{get;set;}

    }

    Is there any way,we can change the relation from Id to Order ID as foreign Key

    Can anybody please help on this regards

    Thanks

    Wednesday, September 9, 2015 8:40 AM

Answers

  • Hi Vene545,

    I've tested with a simple tutorial and found the result meets your requirement. Please try the following code and let me know your result.

     public class Project
        {
            public int ProjectId { get; set; }
            public string Name { get; set; }
            public int ManagerId { get; set; }
            [ForeignKey("ManagerId")]
            public Person Manager { get; set; }
        }
        public class Person
        {
            public int ID { get; set; }
            public string Name { get; set; }
        }
    
        public class ProjectContext : DbContext
        {
            public ProjectContext()
                : base("name=ProjectContext")
            {
            }
    
            public ProjectContext(string connString)
                : base(connString)
            {
            }
    
            public System.Data.Entity.DbSet<Project> Projects { get; set; }
    
            public System.Data.Entity.DbSet<Person> Persons { get; set; }
    
        }

    screenshot:

    tutorial link: http://www.codeproject.com/Articles/319366/EF-Code-First-Add-a-Foreign-Key-relationship

    I hope it helps.

    Regards,



    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click HERE to participate the survey.


    Thursday, September 10, 2015 3:24 AM