c# - 该属性不能配置为导航属性

标签 c# entity-framework

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

这是一个 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 中的一对一关系,关系的双方必须具有相同的主键。


事实上,对于您正在做的事情,也许您可​​以尝试在 LoginPatientTherapist 之间使用某种继承,因为此时 Login 可能同时有 PatientTherapist

关于c# - 该属性不能配置为导航属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30677266/

相关文章:

c# - 代码理解问题

c# - EF LINQ 翻译 : complex query

c# - DataAnnotation 和 Code First 使用 Identity 2.2.1 为 ApplicationUser 创建外键

c# - 在 SQL Server 中保存浮点值

c# - 为什么 C# 似乎不关心一致性?

c# - 将带有路径查找的单击移动添加到我当前在 Unity 中的 2D 项目

c# - 如何首先在代码中或使用 ColumnBuilder 将 ROWGUIDCOL 属性指定为 Guid 类型的列?

c# - Entity Framework 代码首先多对多关系不起作用

entity-framework - 在 Entity Framework 中,插入后获取标识列的值

c# - 如何在wpf中的combobox的显示成员中追加常量值?