How to return a JSON in ASP.NET API that has another JSON inside?

Asked

Viewed 44 times

0

I don’t know if my question expresses well, but the kind of feedback I need is something like this:

[
  {
    "Id": 0,
    "Name": "string",
    "Image": "string",
    "Why": "string",
    "What": "string",
    "WhatWillWeDo": "string",
    "ProjStatus": 0,
    "Course": {
      "CourseId": 0,
      "Name": "string"
    },
    "CourseId": 0
  }
]

but in return I get only:

[
  {
    "id": 0,
    "name": "string",
    "image": "string",
    "why": "string",
    "what": "string",
    "whatWillWeDo": "string",
    "projStatus": 0,
    "course": null,
    "courseId": 0
  }
]

method GET in the Controller

public ActionResult<IEnumerable<Project>> Get()
{
    try
    {
        var projects = 
            (from project in _acess.GetProjects()
                select project)
        .ToList();
        return projects;
    }
    catch (Exception ex)
    {
        return null;
    }
}

class that is called in the Controller

public IEnumerable<Project> GetProjects()
{
    // var aux = context
    //  .Projects
    //  .ToList()
    //  .Count;
    return context.Project.ToList();
}

the class of projects

public class Project
{
    [Key]
    public int Id { get; set; }
    [Required(ErrorMessage = "Nome é obrigatório")]
    public string Name { get; set; }
    public string Image { get; set; }
    public string Why { get; set; }
    public string What { get; set; }
    public string WhatWillWeDo { get; set; }
    public ProjectStatus ProjStatus { get; set; }
    public Course Course { get; set; }

    public int CourseId { get; set; }

    public enum ProjectStatus
    {
        development = 0,
        publicated = 1
    }
}

1 answer

2


If you are using EntityFramework, properties that are also being mapped within the entity need to be included in the query, try something like:

context.Project.Where(i => i.CourseId == id).Include("Course").FirstOrDefault();

or

context.Project.Where(i => i.CourseId == id).Include(x => x.Course).FirstOrDefault();
  • Thank you very much, I managed to use the code and returned the JSON the way I expected. However, when I try to use this code together with context.project.Include("Course"). Find(id) does not work, even if I use context.project.Where(i => i.Id== id). Include("Course") this way. You would have some hint?

  • @Tester what is the error message? Why doesn’t it work?

  • 1

    I was putting the method incorrectly without noticing, it is working yes. Thanks for the help.

  • @Marvel Tester, don’t forget to mark as answered :D

  • Sorry ignorance, but where mark as answered? I am looking for the site and can not find option.

  • @Tester In the upper left corner of my answer you should have a check

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.