我认为这是一个非常基本的问题,但我似乎无法让它正常工作。所以,我正在使用Model-First使用EF6 Framework建立一个MVC 5项目。为了简化事情,我要说我有4个模型:学生,老师,家长,地址。学生,教师和家长共享相似的字段,所以我想创建一个继承的Person基类。我这样做没有问题,但我的问题是将地址记录与一个人联系起来。从人到地址,我会有1到1:0的关系。所以,我的Address类看起来像这样..
public class Address
{
public int ID { get; set; }
public string StreetLine1 { get; set; }
public string StreetLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZipCode { get; set; }
[Key]
[ForeignKey("Person")]
public int PersonID { get; set; }
public virtual Person person { get; set; }
}
我的Person类看起来像这样......
public abstract class Person
{
public int ID { get; set; }
[Required]
[StringLength(50,ErrorMessage = "First Name cannot be longer than 50 characters.")]
[Display(Name= "First Name")]
public string FirstName { get; set; }
[StringLength(50, ErrorMessage = "Middle Name cannot be longer than 50 characters.")]
[Display(Name = "Middle Name")]
public string MiddleName { get; set; }
[Required]
[StringLength(50, ErrorMessage = "Last Name cannot be longer than 50 characters.")]
[Display(Name = "Last Name")]
public string LastName { get; set; }
public PersonType personType {get; set;}
[Key]
[ForeignKey("Address")]
public int AddressID { get; set; }
public virtual Address Address { get; set; }
[Display(Name = "Full Name")]
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
[Display(Name = "Full Name w Middle")]
public string FullNameWMid
{
get
{
return FirstName + " " + MiddleName + " " + LastName;
}
}
}
我的学生班定义为......
public class Student : Person
{
[DataType(DataType.Date)]
[DisplayFormat(DataFormatString = "{0:mm-dd-yyyy}", ApplyFormatInEditMode = true)]
[Display(Name = "Birthday")]
public DateTime Birthday { get; set; }
public virtual ICollection<Parent> Parents { get; set; }
public virtual Teacher teacher { get; set; }
}
所以,当我尝试为Student创建一个新的控制器时,我的问题就出现了。我收到一个错误,无法检索Student的元数据,因为类型Address上的ForeignKey PersonID无效。在依赖类型地址上找不到导航类型Person。
所以,我在地址中明显有一个Person导航类型,并且在Person中有一个Address导航类型,以及AddressID的FK查找。我假设由于继承,这与PersonID与StudentID有关。所以,我确实尝试更改为在地址中使用导航类型的学生,然后在学生中放置地址导航类型。当我这样做时,我得到与上面相同的错误,就Person / PersonID而言。我确信这是我缺少的一个基本的OOO原则,但我很感激任何指导,弄清楚我做错了什么!
提前致谢!