I am building a ASP.NET Core 2.0 application with a Web API backend and an Angular 5 front end. For my data access layer I am using Entity Framework Core.
For example, I have two models below that have a relationship.
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; }
}
However when I try and connect to the database and retrieve these to display, EF Core states that it does not understand the relationship between Project.pm_person_id and Person.
I followed the microsoft documentation on EF Core and the ForeignKey attribute is what it recommended, as opposed to defining these in the ModelBuilder. Have I fully established the relationship correctly?
in the class Project you must add the using
and the class Project should be modeled in this way:
and add the icollection in the class Person
try this!