我刚开始编码第一个approch刚才开始学习我已经创建了两个类,但是显示了这样的错误。必须在具有一个*关系的类中进行更改。 这两个类是,
[Table("Department")]
public class Department
{
[Key]
public int Did { get; set; }
public int DName { get; set; }
public virtual Student student { get; set; }
}
[Table("Student")]
public class Student
{
[Key]
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
public int? department { get; set; }
[ForeignKey("department")]
public virtual Department Department { get; set; }
}
我的上下文类:
public class StudentContext : DbContext
{
public StudentContext()
:base("StudentContext")
{ }
public DbSet<Student> students { get; set; }
public DbSet<Department> departments { get; set; }
}
答案 0 :(得分:0)
嗯,首先,你有2个部门属性。您可能希望外键是DepartmentId。那么你需要1对多的学生集合。
// No need for a table attribute if it matches the class name
public class Department
{
[Key] // If you called this Id or DepartmentId you would not need the attribute
public int Did { get; set; }
public int DName { get; set; }
public virtual ICollection<Student> Students { get; set; }
}
public class Student
{
[Key]
public int id { get; set; }
public string name { get; set; }
public int age { get; set; }
// EF will make this relationship automatically. But if you like you can keep FK attribute.
[ForeignKey("Department")]
public int? DepartmentId { get; set; }
public virtual Department Department { get; set; }
}