简体   繁体   English

带有列表的 POST 方法<t> object 与 EF Core 5.0 API</t>

[英]POST method with List<T> object with EF Core 5.0 API

So I'm new to coding in general and starting to work with .net core 5.0.所以我一般是编码新手,开始使用 .net 核心 5.0。 I'm trying to develop a simple API with Entity Framework Core and I'm having problems when I try to use the POST method.我正在尝试使用 Entity Framework Core 开发一个简单的 API,但在尝试使用 POST 方法时遇到问题。 I have a class called Question and another one called Template, which goes as follows我有一个名为 Question 的 class 和另一个名为 Template 的 class,如下所示

public class Question
{
    public int Id { get; set; }
    public string Answer { get; set; }
    public int Weight { get; set; }
}

public class Template
{
    public int Id { get; set; }
    public List<Question> Questions { get; set; }
}

When I go to Postman with my API running, I enter the following into the POST method:当我在 API 运行的情况下运行 go 到 Postman 时,我在 POST 方法中输入以下内容:

{
    "questions" : [
    {   "answer" : "a", "weight" : 2  },
    {   "answer" : "b", "weight" : 2  },
    {   "answer" : "c", "weight" : 2  },
    {   "answer" : "d", "weight" : 2  },
    {   "answer" : "a", "weight" : 1  },
    {   "answer" : "b", "weight" : 1  }
    ]
}

But what I get as a response when I call the GET method is something of the sort但是当我调用 GET 方法时,我得到的响应是这样的

[
   {
      "id": 1,
      "questions": null
   },
   {
      "id": 2,
      "questions": null
   }
]

This is the code part with POST and GET in my TemplatesController class这是我的 TemplatesController class 中带有 POST 和 GET 的代码部分

[Route("api/[controller]")]
[ApiController]
public class TemplatesController : ControllerBase
{
    private readonly AlfContext _context;

    public TemplatesController(AlfContext context)
    {
        _context = context;
    }

    // GET: api/Templates
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Template>>> GetTemplates()
    {
        return await _context.Templates.ToListAsync();
    }

    // GET: api/Templates/5
    [HttpGet("{id}")]
    public async Task<ActionResult<Template>> GetTemplate(int id)
    {
        var template = await _context.Templates.FindAsync(id);

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

        return template;
    }

    // POST: api/Templates
    [HttpPost]
    public async Task<ActionResult<Template>> PostTemplate(Template template)
    {
        _context.Templates.Add(template);
        await _context.SaveChangesAsync();

        return CreatedAtAction(nameof(GetTemplate), new { id = template.Id }, template);
    }

    private bool TemplateExists(int id)
    {
        return _context.Templates.Any(e => e.Id == id);
    }
}

And here is my DbContext class这是我的 DbContext class

public class AlfContext : DbContext
{
    public DbSet<Template> Templates { get; set; }

    public AlfContext(DbContextOptions<AlfContext> options)
        : base(options)
    {
    }
} 

Why do I keep receiving "null" as a response in my "questions" field?为什么我在“问题”字段中不断收到“null”作为响应? Am I missing something, or maybe a concept?我错过了什么,或者可能是一个概念?

Based on your question there, with my experience, I would like you to make sure:根据您的问题,以我的经验,我希望您确保:

  1. On post, is data saving correctly into question entity.在发布时,数据是否正确保存到问题实体中。

  2. If so, on get mapping, make sure that your child entities are loaded using eager loading.如果是这样,在获取映射时,请确保您的子实体使用预加载加载。 (like efcore.include() to load the child entities) (如 efcore.include() 加载子实体)

If not using any external mappers, Note: Make sure to add a constructor initializing your list.如果不使用任何外部映射器,请注意:确保添加初始化列表的构造函数。

public class Template
{
    public int Id { get; set; }
    public List<Question> Questions { get; set; }
    public Template()
    {
       Questions = new List<Questions>()
    }
}

Kindly please do have a try with this and let me know if you need additional information from my end.请尝试一下,如果您需要我提供的其他信息,请告诉我。

You are not asking for the related Question entities in your query.您不是在查询中询问相关的Question实体。

Modify your GET method to -将您的 GET 方法修改为 -

[HttpGet]
public async Task<ActionResult<IEnumerable<Template>>> GetTemplates()
{
    return await _context.Templates.Include(p=> p.Questions).ToListAsync();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM