Return 来自 Web api 使用 Entity Framework 和导航属性的嵌套列表

Return nested List from web api using Entity Framework and navigation properties

我正在尝试 return 一个 JSON 和一个使用导航属性的嵌套列表,但我一直在 'Usuario' 集合中得到 null 这是输出。

 [
  {
    "$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": []
  }
]

这是我的 .edmx

最后,这是我拥有网络的地方 ​​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;

            }
        }
    }
}

我从 Getting a related collection 那里收到了他的询问,但我仍然遇到问题,我将不胜感激任何帮助

你应该使用 Eager Loading:

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

旁注 - 似乎您的所有 Preguntas 实体都将具有相同的 Usuario 实体,id = 1。此外,您不需要为 ToList 方法指定通用参数 - 应该推断出参数。