【问题标题】:Return nested List from web api using Entity Framework and navigation properties使用实体框架和导航属性从 web api 返回嵌套列表
【发布时间】:2016-12-06 17:02:57
【问题描述】:

我正在尝试使用导航属性返回带有嵌套列表的 JSON,但我在“Usuario”集合中一直为空,这是输出。

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

最后这就是我拥有 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;

            }
        }
    }
}

我从 Getting a related collection 收到了他的问题,但我仍然遇到问题,我将不胜感激

【问题讨论】:

    标签: json asp.net-mvc entity-framework asp.net-web-api ado.net


    【解决方案1】:

    你应该使用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 方法指定通用参数 - 应该推断参数。

    【讨论】:

    • 谢谢 Sergey,我遇到了问题,因为我没有导入 Systems.Data.Entity 并且我从其他库中获取了 Include 方法。但效果很好,再次感谢。
    猜你喜欢
    • 2016-09-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-07
    相关资源
    最近更新 更多