1

所以基本上我有一个学生表,其中包含一个人表所需的外键。我的课程设置如下:

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。 . .

在此先感谢,

4

2 回答 2

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;
        }
    }
于 2013-10-16T05:53:25.877 回答
0

EF 代码的默认行为首先是以这种方式命名您的外键:Person_ID. 你打电话给你的 property PersonID,所以 EF 没有意识到这应该是你的外键。在您的数据库内部,创建了一个名为的列,该列Person_ID未映射到您的模型中。

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

public int PersonID { get; set; }

[ForeignKey("PersonID")]
public virtual Student Student { get; set; }
于 2013-10-16T05:25:04.400 回答