ASP.NET核心Webapi父子关系



我正在.net core 2.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; }
}

和DbContext:

public class TaskManagerDbContext : DbContext
{
public TaskManagerDbContext(DbContextOptions<TaskManagerDbContext> options) 
: base(options) { }
public DbSet<Project> Projects { get; set; }
public DbSet<Task> Tasks { get; set; }
}

我做了一个迁移和更新数据库。

下一步是基于Entity框架制作具有读/写操作的WebAPI控制器。

我的问题是,为什么当我尝试调试我的代码tasks列表时,它没有被重新分配给Project?

我尝试了硬编码的任务和项目。一切都很好,当我调用简单的api/Projects作为响应时,我得到了"tasks": null。你能帮我在WebApi控制器中关联这些信息吗?

控制器看起来像这样:

[Route("api/[controller]")]
[ApiController]
public class ProjectsController : ControllerBase
{
private readonly TaskManagerDbContext _context;
public ProjectsController(TaskManagerDbContext context)
{
_context = context; //tasks in projects here are null
}
// GET: api/Projects
[HttpGet]
public IEnumerable<Project> GetProjects()
{
return _context.Projects;
}
}

并通过框架生成了其标准控制器。我可以很好地(通过生成的控制器(以这种方式获得项目和任务。但项目与tasks无关。

如何包含tasksProject

按如下方式编写GetProjects方法:

[HttpGet]
public IEnumerable<Project> GetProjects()
{
return _context.Projects.Include(p => p.Tasks).ToList();
}

然后为了避免Self referencing loop,在Startup类的ConfigureServices方法中添加以下配置:

public void ConfigureServices(IServiceCollection services)
{
...
services.AddMvc()
.AddJsonOptions(
options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
...
}

您可以使用include,如下所示。您将在项目集合中获得任务集合

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

最新更新