如何使用代码优先Fluent API将属性设置为一对一关系中的外键?

时间:2017-06-07 20:05:28

标签: asp.net-mvc entity-framework-6 ef-fluent-api

我有两类Student和StudentAddress。学生有一个地址的地方。现在,如何使用Fluent API将Student类的主键StudentId设置为StudentAddress类的外键。我想要一个不同的属性,如StudentId将成为StudentAddress中的外键。我怎样才能做到这一点? (我正在使用Entity Framework 6)。这是我的课程。

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 个答案:

答案 0 :(得分:1)

您可以使用以下代码轻松完成此操作:

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); 

}

仅限FYI,不含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; }
}

有关其他信息:http://www.entityframeworktutorial.net/code-first/configure-one-to-one-relationship-in-code-first.aspx

希望以上信息有用。

由于

KARTHIK