0
votes

I have two class of Student and StudentAddress. Where a Student have one Address. Now How can I set the Primary key StudentId of the Student class as the Foreign key of the StudentAddress class using Fluent API. I want a different property such as StudentId will be the Foreign key in StudentAddress. How can i do this? (I am using Entity Framework 6). Here is my classes.

public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }

    //Navigation property
    public virtual StudentAddress StudentAddress { get; set; }
}
public class StudentAddress
{

    public int StudentAddressId { get; set; }
    public int StudentId { get; set; }  //Set this property as a forign key
    public string Address { get; set; }
    //Navigation property
    public virtual Student Student { get; set; }

}
1
You can't do it that way. The general technique is to make StudentAddress's StudentId both the PK and FK. See here - Steve Greene
Yes i have also seen that. But I was not sure about was it my coding problem or was i missing something. Thank you. - Sujon Chondro Shil

1 Answers

1
votes

you can easily do that , with the following code:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // Configure StudentId as PK for StudentAddress
    modelBuilder.Entity<StudentAddress>()
        .HasKey(e => e.StudentId);

    // Configure StudentId as FK for StudentAddress
    modelBuilder.Entity<Student>()
                .HasOptional(s => s.Address) 
                .WithRequired(ad => ad.StudentId); 

}

Just FYI without Fluent API:

public class Student
{
    public Student() { }

    public int StudentId { get; set; }
    public string StudentName { get; set; }

    public virtual StudentAddress Address { get; set; }

}

public class StudentAddress 
{
    [Key, ForeignKey("Student")]
    public int StudentId { get; set; }

    public string Address1 { get; set; }
    public string Address2 { get; set; }
    public string City { get; set; }
    public int Zipcode { get; set; }
    public string State { get; set; }
    public string Country { get; set; }

    public virtual Student Student { get; set; }
}

For additional info: http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

Hope above information was helpful.

Thanks

Karthik