我有两类的学生和学生。学生有一个地址。现在,我如何使用Fluent API将学生班的主要钥匙学生设置为StudentAddress类的外键。我希望诸如StudentId之类的其他财产将成为StudentAddress中的外键。我怎样才能做到这一点?(我使用实体框架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; }
}
您可以使用以下代码轻松地做到这一点:
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);
}
只有不流利的API的fyi:
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.entityframeworkturorial.net/code-first/configure-one-oone-to-one-realationship-in-code-first.aspx
希望上述信息很有帮助。
谢谢
karthik