该属性不能配置为导航属性

问题描述 投票:5回答:1

我正在尝试实现这样的域模型:My model

这是一个实体框架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; }
}

我完全按照教程和堆栈溢出问题进行操作,无论我做什么,当我尝试运行控制器时,我都会得到同样的错误:

无法检索“患者”的元数据。属性“TherapistId”无法配置为导航属性。该属性必须是有效的实体类型,并且该属性应具有非抽象的getter和setter。对于集合属性,类型必须实现ICollection,其中T是有效的实体类型

我不知道TherapistId有什么问题 - 也许整个模型的想法都是垃圾?

c# entity-framework
1个回答
18
投票

我认为你在这种情况下的具体错误就是你有

[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中的一对一关系,关系的两侧必须具有相同的主键。


事实上,对于你正在做的事情,也许你可以尝试在LoginPatientTherapist之间使用某种类型的继承,因为目前,Login可能同时具有PatientTherapist

© www.soinside.com 2019 - 2024. All rights reserved.