实体框架1-1..1关系无法按预期运行

时间:2013-10-16 05:05:54

标签: c# sql entity-framework

所以基本上我有一个Student表,它包含一个Person表所需的外键。我按如下方式设置了我的课程:

class Person
{
    public int PersonID { get; set; }
    public string Phone_Number { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }

    //navigation properties
    public virtual Student Student { get; set; }

    public override string ToString()
    {
        return Last_Name + ", " + First_Name;
    }
}

class Student
{
    public int StudentID { get; set; }
    public DateTime Dob { get; set; }

    public int PersonID { get; set; }
    public int Student_TypeID { get; set; }

    //navigation properties
    [Required]
    public virtual Person Person { get; set; }
}

每当我尝试添加如下新学生时,人的外键仍为0:

Student student = new Student
{
    Dob = dpStudentDob.Value,
    Student_TypeID = (rdoStudentRegular.Checked) ? 1 : 2,
    Person = new Person
    {
        First_Name = txtStudentFirstName.Text,
        Last_Name = txtStudentLastName.Text,
        Address = txtStudentAddress.Text,
        Email = txtStudentEmail.Text,
        Phone_Number = txtStudentPhoneNum.Text
    }
};

using (var context = new MusicSchoolDB())
{
    context.Students.Add(student);
    context.SaveChanges();
}

无论我添加学生多少次,人的外键仍为0。

提前致谢, Ĵ

2 个答案:

答案 0 :(得分:0)

首先,EF代码的默认行为是以这种方式命名您的外键:Person_ID。您调用了属性PersonID,因此EF没有意识到这应该是您的外键。在数据库内部,创建了一个名为Person_ID的列,该列未在模型中映射。

使用数据注释,您可以明确告诉EF您的外键属性是什么:

public int PersonID { get; set; }

[ForeignKey("PersonID")]
public virtual Student Student { get; set; }

答案 1 :(得分:0)

试试这个,

class Student
    {
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int StudentID { get; set; }
        public DateTime Dob { get; set; }

        [ForeignKey("Person")]
        [Key]
        public int PersonID { get; set; }
        public int Student_TypeID { get; set; }

        //navigation properties
        public virtual Person Person { get; set; }
    }

class Person
    {
        [Key]
        public int PersonID { get; set; }
        public string Phone_Number { get; set; }
        public string Email { get; set; }
        public string Address { get; set; }
        public string First_Name { get; set; }
        public string Last_Name { get; set; }

        //navigation properties
        public virtual Student Student { get; set; }

        public override string ToString()
        {
            return Last_Name + ", " + First_Name;
        }
    }