0

I'm trying to return a JSON with a nested list using Navigation properties but I keep getting null in the 'Usuario' collection here's the output.

 [
  {
    "$id": "1",
    "id": 1,
    "encabezado": "Como llamar a un metodo en c#",
    "cuerpo": "Estoy intentando llamar un metodo metodo() pero no puedo alguna sugerencia xD?",
    "points": 0,
    "Usuario": null,
    "Respuestas": []
  },
  {
    "$id": "2",
    "id": 2,
    "encabezado": "Como cambiar conection String",
    "cuerpo": "Es posible cambiar el conection string en asp.net si ya esta creada?",
    "points": 1,
    "Usuario": null,
    "Respuestas": []
  }
]

here's my .edmx

enter image description here

And finally this is where I have the web api

namespace AskTecProject.Controllers
{
    public class QuestionController : ApiController
    {
        [HttpGet]
        public List<Pregunta> GetQuestions()
        {
            using (asktecdbEntities entities = new asktecdbEntities())
            {
                List<Pregunta> p = entities.Usuarios.Where(m => m.id.Equals(1)).SelectMany(m => m.Preguntas).ToList<Pregunta>();
                return p;

            }
        }
    }
}

I got his query from Getting a related collection but I'm still having trouble with this, I'll appreciate any help

1 Answer 1

2

You should use Eager Loading:

List<Pregunta> preguntas = entities.Usuarios
       .Where(u => u.id.Equals(1))
       .SelectMany(u => u.Preguntas)
       .Include(p => p.Usuario) // here
       .ToList<Pregunta>();

Side note - seems like all your Preguntas entities will have same Usuario entity with id = 1. Also you don't need to specify generic parameter for ToList method - parameter should be inferred.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you Sergey, I was having trouble for a second, cause I didn't had Systems.Data.Entity imported and I was getting the Include method from other library. But It works great, thanks again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.