如何在EntityFramework中定义一对一或零关系

时间:2017-02-22 01:44:41

标签: entity-framework one-to-one

我有一个学生实体,其外键 HouseID 引用一般表格中的 GeneralID 列。我在模型中正确定义了吗?

Student.cs

public class Student
{
    public int studentID { get; set; }
    public Nullable<int> houseID { get; set; }
    public virtual House House { get; set; }
  }

 public class House
{
    [Key, ForeignKey("Student"), Column("GeneralID")]
    public int houseID { get; set; }

    public virtual Student Student { get; set; }
}

更新 我在GEDBContext类中的OnModelCreating()包含

 modelBuilder.Entity<Student>()
            .HasOptional<House>(s => s.House)
            .WithOptionalDependent(h => h.Student);

更新2

我已将学生和家庭课程改为:

 public class House
{
    [Key, Column("GeneralID")]
    public int houseID { get; set; }

    public virtual ICollection<Student> Students { get; set; }
}

public class Student
{
    public int studentID { get; set; }

    [ForeignKey("HouseID")]
    public Nullable<int> houseID { get; set; }
    public virtual House House { get; set; }
  }

0 个答案:

没有答案