【问题标题】:ASP.Net Core related models field required errorASP.Net Core 相关模型字段必填错误
【发布时间】:2017-03-23 01:29:18
【问题描述】:

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

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 相关字段,我也希望能够发布或放置数据。现在我只有 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();
    }
}

【问题讨论】:

  • 当你有 contextId 时,为什么你需要在你的连接类中使用上下文,如果你拿出对你有用的东西?
  • 这是我第一次使用 asp.net core,我正在关注模型关系教程 (docs.microsoft.com/en-us/ef/core/modeling/relationships),它是在那里给出的。我正在构建 Web Api,在这种情况下不需要此导航属性?
  • @Nitish 你能告诉我控制器类吗?
  • @Turbot 我用控制器更新了我的问题。此外,如果我从连接中删除上下文,错误就消失了。但是,我在 repo 中的更新方法仍然存在某种错误。如果我尝试将更新的数据放入现有连接(在特定上下文中),则会引发错误。
  • 你能发布服务器异常吗?

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


【解决方案1】:

这是因为您在关系字段中错过了虚拟关键字。这里在 Context 类的 Connections 字段中添加 virtual 关键字

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

连接类中的上下文将解决问题

 public virtual Context Context { get; set; }

更多信息请阅读this anwser

【讨论】:

  • 添加虚拟后是否需要迁移和更新数据库?另外,如果我正在构建 Web API(参考我的问题的第一条评论),public virtual Context Context { get; set; } 是否有必要?
  • 不这么认为...实际上这取决于您的映射..您是否将 Connection 中的 ContextId 字段映射为数据库中的外键
  • 不,不明确。看到我的模型有问题,这就是你所指的对吗?
  • 如果你把上下文字段的 [ForeignKey("ContextId ")] 属性放在连接中会很好
  • 好的,如果它是一个 Web API,我真的需要 public Context Context { get; set; } 连接吗?因为只有在删除它之后,我才能得到原始错误(请参阅我的问题下方的 cmets)
猜你喜欢
  • 2016-07-04
  • 2022-08-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多