C# ASP.NET核心Webapi父子关系?

C# ASP.NET核心Webapi父子关系?,c#,asp.net-web-api,asp.net-core,entity-framework-core,C#,Asp.net Web Api,Asp.net Core,Entity Framework Core,我正在.NETCore2.1中开发我的webapi 我有两种型号: public class Project { [Key] public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ICollection<Task> Tasks { get; set; } //list of task

我正在.NETCore2.1中开发我的webapi

我有两种型号:

public class Project
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    public ICollection<Task> Tasks { get; set; } //list of tasks

}

public class Task
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }

    [ForeignKey("Project")]
    public int ProjectId { get; set; } //project that task is included
    public Project Project { get; set; }
}
其标准控制器由框架生成。我可以通过这种方式(通过生成的控制器)很好地获得项目和任务。但是项目没有相关的
任务


如何将
任务
包含到
项目

您可以像下面这样使用include。您将在项目集合中获得tasks集合

// GET: api/Projects
    [HttpGet]
    public IEnumerable<Project> GetProjects()
    {
        return _context.Projects.Include(x=>x.Task);
    }
//GET:api/Projects
[HttpGet]
公共IEnumerable GetProjects()
{
return\u context.Projects.Include(x=>x.Task);
}

按如下方式编写
GetProjects
方法:

[HttpGet]
public IEnumerable<Project> GetProjects()
{
    return _context.Projects.Include(p => p.Tasks).ToList();
}
// GET: api/Projects
    [HttpGet]
    public IEnumerable<Project> GetProjects()
    {
        return _context.Projects.Include(x=>x.Task);
    }
[HttpGet]
public IEnumerable<Project> GetProjects()
{
    return _context.Projects.Include(p => p.Tasks).ToList();
}
public void ConfigureServices(IServiceCollection services)
{
    ...

    services.AddMvc()
        .AddJsonOptions(
            options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
        );

    ...
}