【问题标题】:How to set a property as a foreign key in One to one Relationship using code-first Fluent API ?如何使用代码优先 Fluent API 将属性设置为一对一关系中的外键?
【发布时间】:2017-06-07 20:05:27
【问题描述】:

我有两类 Student 和 StudentAddress。学生有一个地址。现在如何使用 Fluent API 将 Student 类的主键 StudentId 设置为 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; }

}

【问题讨论】:

  • 你不能那样做。一般的技术是让StudentAddress 的StudentId 成为PK 和FK。见here
  • 是的,我也看到了。但我不确定是我的编码问题还是我遗漏了什么。谢谢。

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


【解决方案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); 

}

仅供参考,没有 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

希望以上信息对您有所帮助。

谢谢

卡提克

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-28
    • 2015-07-29
    • 1970-01-01
    • 2012-04-23
    • 2016-01-31
    • 1970-01-01
    • 2018-05-31
    • 1970-01-01
    相关资源
    最近更新 更多