0

我在.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; }
}

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

下一步是制作基于实体框架的具有读/写操作的 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

4

2 回答 2

1

编写您的GetProjects方法如下:

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

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

public void ConfigureServices(IServiceCollection services)
{
    ...

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

    ...
}
于 2018-12-18T13:30:23.970 回答
0

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

// GET: api/Projects
    [HttpGet]
    public IEnumerable<Project> GetProjects()
    {
        return _context.Projects.Include(x=>x.Task);
    }
于 2018-12-18T13:28:05.630 回答