michasacuer2
michasacuer2

Reputation: 65

ASP .NET Core Webapi Parent - Child relation?

Im working on my webapi in .net core 2.1

I have Two models:

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; }
}

And DbContext:

public class TaskManagerDbContext : DbContext
{
    public TaskManagerDbContext(DbContextOptions<TaskManagerDbContext> options) 
      : base(options) { }

    public DbSet<Project> Projects { get; set; }
    public DbSet<Task> Tasks { get; set; }
}

I made an migration and update-database.

The next step was make WebAPI Controllers with Read/Write action based on Entity framework.

My question is, why when i try to debug my code tasks list is not realated to Project?

I tried hard coded tasks and projects. All works great, byt when i call simple api/Projects in response i get "tasks": null. Could you help me related that information in WebApi controller?

Controller look like this:

[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;
    }
}

And its standard controller genereted by framework. I can get projects and tasks in that way pretty well (by generated controller). But Projects have not tasks related.

How to include tasks to Project?

Upvotes: 0

Views: 3186

Answers (2)

TanvirArjel
TanvirArjel

Reputation: 32109

Write your GetProjects method as follows:

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

Then to avoid Self referencing loop add the following configuration in the ConfigureServices method of the Startup class:

public void ConfigureServices(IServiceCollection services)
{
    ...

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

    ...
}

Upvotes: 1

sri harsha
sri harsha

Reputation: 680

you can use include like below. And you will get the tasks collection inside projects collection

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

Upvotes: 0

Related Questions