【发布时间】:2018-04-19 19:16:14
【问题描述】:
我正在构建一个带有 Web API 后端和 Angular 5 前端的 ASP.NET Core 2.0 应用程序。对于我的数据访问层,我使用的是 Entity Framework Core。
例如,我下面有两个模型有关系。
public class Project
{
[Key]
public int Id { get; set; }
public string project_name { get; set; }
[ForeignKey("Person")]
public int? pm_person_id { get; set; }
[ForeignKey("Person")]
public int? ptl_person_id { get; set; }
[ForeignKey("pm_person_id")]
public virtual Person pm_person { get; set; }
[ForeignKey("ptl_person_id")]
public virtual Person ptl_person { get; set; }
}
public class Person
{
public Person()
{
pm_projects = new HashSet<Project>();
ptl_projects = new HashSet<Project>();
}
[Key]
public int Id { get; set; }
public string full_name { get; set; }
[ForeignKey("pm_person_id")]
public virtual ICollection<Project> pm_projects { get; set; }
[ForeignKey("ptl_person_id")]
public virtual ICollection<Project> ptl_projects { get; set; }
}
但是,当我尝试连接到数据库并检索这些以显示时,EF Core 表示它不理解 Project.pm_person_id 和 Person 之间的关系。
我遵循了 EF Core 上的 Microsoft 文档,它建议使用 ForeignKey 属性,而不是在 ModelBuilder 中定义这些属性。我是否完全正确地建立了关系?
【问题讨论】:
-
在
Person类上,尝试将[ForeignKey("ptl_person_id")]更改为[ForeignKey("ptl_person")],同样适用于[ForeignKey("pm_person_id")](也在Person上)。
标签: c# asp.net-core entity-framework-4.1