ASP.Net核心相关模型字段必填错误

时间:2017-03-22 13:46:17

标签: asp.net-core entity-framework-core asp.net-core-webapi

我有两个相关的模型如下:

public class Context
    {
        [Key]
        public long ContextId { get; set; }
        [Required]
        public string Role { get; set; }

        public ICollection<Connection> Connections { get; set; }

        public Context()
        {

        }
    }

public class Connection
    {
        [Key]
        public long ConnectionId { get; set; }
        public string Name { get; set; }

        public long ContextId { get; set; }
        public Context Context { get; set; }

        public Connection()
        {

        }
    }

我有 Context 的存储库:

public class ContextRepository: IContextRepository
{
    private readonly WebAPIDataContext _db;

    public ContextRepository(WebAPIDataContext db)
    {
        _db = db;
    }

    public Context CreateContext(Context context)
    {
        _db.Contexts.Add(context);
        _db.SaveChanges();
        return context;
    }

    public void DeleteContext(long id)
    {
        Context context = GetContext(id);
        if (context != null)
        {
            _db.Contexts.Remove(context);
            _db.SaveChanges();
        }
    }

    public List<Context> GetAllContexts()
    {
        return _db.Contexts
            .Include(context => context.Connections)
            .ToList();
    }

    public Context GetContext(long id)
    {
        return _db.Contexts.FirstOrDefault(o => o.ContextId == id);
    }

    public void UpdateContext(long id, Context context)
    {
        Context contextToUpdate = _db.Contexts.FirstOrDefault(o => o.ContextId == id);
        contextToUpdate.Role = context.Role;
        contextToUpdate.Connections = context.Connections;
        _db.Update(contextToUpdate);
        _db.SaveChanges();

    }
}

Swagger给了我如下骨架:

{
  "contextId": 0,
  "role": "string",
  "connections": [
    {
      "connectionId": 0,
      "name": "string",
      "contextId": 0,
      "context": {}
    }
  ]
}

如果我填写"Role":"Worker""name":"Max"并在PUT中执行POST或类似操作,那么它会给我错误:

{
  "Connections[0].Context.Role": [
    "The Role field is required."
  ]
}

为什么会这样?即使我没有填写connections相关字段,我也希望能够POST或PUT数据。现在我只有 Context 的控制器。

更新:控制器:

[Route("api/[controller]")]
public class ContextController : Controller
{
    private readonly IContextRepository _contexts;
    public ContextController(IContextRepository contexts)
    {
        _contexts = contexts;
    }

    [HttpGet("")]
    public IActionResult GetAllContexts()
    {
        try
        {
            List<Context> contexts = _contexts.GetAllContexts();
            return Ok(contexts);
        }
        catch (EntityNotFoundException<Context>)
        {
            return NotFound();
        }

    }

    [HttpGet("{id}")]
    public IActionResult GetContext(long id)
    {
        Context context= _contexts.GetContext(id);
        if (context == null)
        {
            return NotFound();
        }
        return Ok(context);
    }

    [HttpPost]
    public IActionResult CreateContext([FromBody] Context context)
    {
        if (ModelState.IsValid == false)
        {
            return BadRequest(ModelState);
        }

        Context createdContext= _contexts.CreateContext(context);
        if (createdContext== null)
        {
            return NotFound();
        }
        return CreatedAtAction(
             nameof(GetContext), new { id = createdContext.ContextId}, createdContext);

    }

    [HttpPut("{id}")]
    public IActionResult UpdateContext(long id, [FromBody] Context context)
    {
        if (ModelState.IsValid == false)
        {
            return BadRequest(ModelState);
        }

        try
        {
            _contexts.UpdateContext(id, context);
            return Ok();
        }
        catch (EntityNotFoundException<Context>)
        {
            return NotFound();
        }
    }

    [HttpDelete("{id}")]
    public IActionResult DeleteCOntext(long id)
    {
        _contexts.DeleteContext(id);
        return Ok();
    }
}

1 个答案:

答案 0 :(得分:0)

这是因为您在关系字段中遗漏了虚拟关键字。这里将虚拟关键字添加到Context类

中的Connections字段
 public virtual ICollection<Connection> Connections { get; set; }

和Context in Connection类将解决问题

 public virtual Context Context { get; set; }

有关详细信息,请参阅this anwser