这是一个 Entity Framework mvc 应用程序。该模型的代码如下所示:
public class Login
{
[Key]
public int LoginID { get; set; }
public virtual Therapist Therapist { get; set; }
public virtual Patient Patient { get; set; }
}
public class Patient
{
[Key]
[ForeignKey("Login")]
[Display(Name = "No.")]
public int PatientId { get; set; }
[ForeignKey("Therapist")]
public int TherapistId { get; set; }
[ForeignKey("Therapist")]
public int TherapistId{ get; set; }
public virtual Therapist Therapist { get; set; }
public virtual Login Login { get; set; }
}
public class Therapist
{
[Key]
[ForeignKey("Login")]
[Display(Name = "No.")]
public int TherapistId { get; set; }
[ForeignKey("Login")]
public int LoginId { get; set; }
public virtual Login Login { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
}
我完全按照教程和堆栈溢出问题中的内容进行操作,无论我做什么,当我尝试运行 Controller 时,我都会遇到相同的错误:
Unable to retrieve metadata for 'Patient'. The property "TherapistId" cannot be configured as navigation property. The property must be a valid entity type and the property should have non-abstract getter and setter. For collection properties the type must implement ICollection where T is a valid entity type
我不知道 TherapistId
有什么问题 - 也许模型的整个想法都是垃圾?
最佳答案
我认为你在这种情况下的具体错误是你有
[ForeignKey("TherapistId")]
public int? TherapistId { get; set; }
代替
[ForeignKey("Therapist")]
public int? TherapistId { get; set; }
无论如何,你似乎确实有一些问题,也许是这样的(我只保留了关系属性):
public class Login
{
[Key]
public int LoginID { get; set; }
public virtual Therapist Therapist { get; set; }
public virtual Patient Patient { get; set; }
}
public class Patient
{
[Key]
[ForeignKey("Login")]
[Display(Name = "No.")]
public int PatientId { get; set; }
public virtual Login Login { get; set; }
// was this supposed to be optional?
[ForeignKey("Therapist")]
public int? TherapistId{ get; set; }
public virtual Therapist Therapist { get; set; }
}
public class Therapist
{
[Key]
[ForeignKey("Login")]
[Display(Name = "No.")]
public int TherapistId { get; set; }
public virtual Login Login { get; set; }
public virtual ICollection<Patient> Patients { get; set; }
}
通常,对于 EF 中的一对一关系,关系的双方必须具有相同的主键。
事实上,对于您正在做的事情,也许您可以尝试在 Login
、Patient
和 Therapist
之间使用某种继承,因为此时 Login
可能同时有 Patient
和 Therapist
。
关于c# - 该属性不能配置为导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677266/