即使我强制.include,延迟加载也不起作用

时间:2018-12-11 12:31:35

标签: c# api asp.net-web-api lazy-loading asp.net-core-webapi

我正在尝试获取具有3个值数组的主表,但它根本不起作用。我不知道该如何解决,我正在使用默认的get on controller:

    {
        "userEmail": "user@email.com",
        "createdAt": "2018-12-10T08:02:16.117",
        "update": false,
        "discomfort": [
        {
          "bodyPartId": 1,
          "intensityId": 1,
          "frequencyId": 1
        }
      ],
      "saanswers": [
        {
          "answerId": 1
        }
      ], 
      "sapostures": [
        {
          "postureAnswerId": 1,
          "postureId": 1,
        }
      ]
    }

我想应要求提供什么:

   {
      "userEmail": "user@mail.com",
      "createdAt": "2018-12-10T08:02:16.117",
      "update": false,
      "discomfort": [],
      "saanswers": [],
      "sapostures": []
   }

我正在接收这个Json,但其空数组如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ErgoSAFE_API.Models;

namespace ErgoSAFE_API.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class SelfAssessmentsController : ControllerBase
{
    private readonly ErgoSAFEContext _context;

    public SelfAssessmentsController(ErgoSAFEContext context)
    {
        _context = context;
    }

    // GET: api/SelfAssessments
    [HttpGet]
    public IEnumerable<SelfAssessment> GetSelfAssessment()
    {
        return _context.SelfAssessment;
    }

    // GET: api/SelfAssessments/5
    [HttpGet("{id}")]
    public async Task<IActionResult> GetSelfAssessment([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var selfAssessment = await _context.SelfAssessment.FindAsync(id);

        if (selfAssessment == null)
        {
            return NotFound();
        }

        return Ok(selfAssessment);
    }

    // PUT: api/SelfAssessments/5
    [HttpPut("{id}")]
    public async Task<IActionResult> PutSelfAssessment([FromRoute] int id, [FromBody] SelfAssessment selfAssessment)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        if (id != selfAssessment.SelfAssessmentId)
        {
            return BadRequest();
        }

        _context.Entry(selfAssessment).State = EntityState.Modified;

        try
        {
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!SelfAssessmentExists(id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }

        return NoContent();
    }

    // POST: api/SelfAssessments
    [HttpPost]
    public async Task<IActionResult> PostSelfAssessment([FromBody] SelfAssessment selfAssessment)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        _context.SelfAssessment.Add(selfAssessment);
        await _context.SaveChangesAsync();

        return CreatedAtAction("GetSelfAssessment", new { id = selfAssessment.SelfAssessmentId }, selfAssessment);
    }

    // DELETE: api/SelfAssessments/5
    [HttpDelete("{id}")]
    public async Task<IActionResult> DeleteSelfAssessment([FromRoute] int id)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        var selfAssessment = await _context.SelfAssessment.FindAsync(id);
        if (selfAssessment == null)
        {
            return NotFound();
        }

        _context.SelfAssessment.Remove(selfAssessment);
        await _context.SaveChangesAsync();

        return Ok(selfAssessment);
    }

    private bool SelfAssessmentExists(int id)
    {
        return _context.SelfAssessment.Any(e => e.SelfAssessmentId == id);
    }
}
}

这是我的下面的控制器:

        public IEnumerable<Object> Find (int id) {
        IQueryable<object> entryPoint = (from sa in _context.SelfAssessments
                          join a in _context.Answers on sa.SelfAssessmentId equals a.SelfAssessmentId
                          join q in _context.Questions on a.QuestionId equals q.QuestionId
                          where sa.SelfAssessmentId == id
                          select new {
                              SelfAssessmentID = sa.SelfAssessmentId,
                              Yearly = sa.Yearly,
                              Moved = sa.Moved,
                              CreatedAt = sa.CreatedAt,
                              Question = q.Description,
                              Value = a.Value
                          }).Take(10);
        List<object> result = entryPoint.ToList();

        return result;
    }

.net核心2.1.403

使用VSCode,而不是Visual Studio

编辑1:

[HttpGet]
    public IEnumerable<SelfAssessment> GetSelfAssessment()
    {
        var qry = from s in _context.SelfAssessment
                  select s;

        var results = qry.Include("Discomfort").ToList();
        results = qry.Include("Sapostures").ToList();
        results = qry.Include("Saanswers").ToList();

        return results;
    }

编辑2:

我在控制器上做了一些更改,当我调试代码时,我看到值即将到来,但是当我尝试返回结果时没有错误。

控制器:

with cnt as (
      select ?.type, count(*) as total
      from table1 a inner join
           table2 b
           on a.typeid = b.id
      group by a.type
select a.region, a.type
from table1 a inner join
     cnt c
     on a.type = c.type
where c.total > 2;

昂首阔步的结果:

代码
未记录

详细信息 错误:确定

回复

代码
200

说明 成功

1 个答案:

答案 0 :(得分:1)

因此,如果问题不是完整的数据,则解决方案应该很容易。 我认为您必须渴望加载嵌套属性。

如果您的模型是:

    public class MainEntity
    {
        public int Id { get; set; }
        ICollection<MiddleEntity> MiddleEntities { get; set; }
        //Other properties...
    }

    public class MiddleEntity
    {
        public int Id { get; set; }

        public int MainEntityId { get; set; }
        public MainEntity MainEntity { get; set; }

        ICollection<InnerEntity> InnerEntities { get; set; }
        //Other properties...
    }

    public class InnerEntity
    {
        public int Id { get; set; }

        public int MiddleEntityId { get; set; }
        public MiddleEntity MiddleEntity { get; set; }
        //Other properties...
    }

解决方案应该是:

    [HttpGet("{Id}")]
    public ActionResult<IEnumerable<MainEntity>> GetMainEntities(int Id)
    {
        var result = _context.MainEtities
            .Include(x => x.MiddleEntities)
                .ThenInclude(y => y.InnerEntities)
            .ToList();

        return Ok(result);
    }