【问题标题】:How to do a post in .net core 2 web api with foreign keys如何使用外键在 .net core 2 web api 中发帖
【发布时间】:2018-03-21 01:54:07
【问题描述】:

我有当前型号:

public class Balance
{
    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Amount { get; set; }
    public string Storage { get; set; }
    public Coin Coin { get; set; }
    public User User { get; set; }
}

public class Coin
{
    public int Id { get; set; }
    public string Code { get; set; }
}

以及下面的方法发帖:

    [HttpPost]
    public async Task<ActionResult> PostNew([FromBody] Balance balance)
    {
        var current_user = await _userManager.FindByNameAsync(this.User.Identity.Name);
        balance.User = current_user;
        try
        {
            if (ModelState.IsValid && balance.Title.Trim() != "")
            {
                if(balance.Amount <= 0)
                {
                    balance.Amount = 0;
                }
                _context.Balance.Add(balance);
                _context.SaveChanges();
                return Ok(Json("Registered new balance!"));
            }
        }
        catch (Exception /*e*/)
        {
            return BadRequest(Json("An error ocurred"));
        }
        return BadRequest(Json("An error ocurred"));
    }

我尝试了多种 JSON 格式来发布信息:

{
"title":"test",
"amount":"50",
"coinid":9
}

{
"title":"test",
"amount":"50",
"coin":9
}

{
"title":"test",
"amount":"50",
"coin": { "id":9 }
}

但是我总是得到一个空对象异常或一个外键 id 设置为空的插入,我试着环顾四周,但找不到任何东西,我对 .net 比较陌生,正在寻求帮助,谢谢你!

编辑:

数据库结构:

【问题讨论】:

  • 尝试添加硬币代码{ "title":"test", "amount":"50","storage":xyz" "coin":{"id":9,"code":"abc"} }
  • @Prashanth 我试过了,但是 "coin" : {...} 所做的是尝试向数据库中添加一个新硬币,所以它所做的只是给我一个“主键约束错误”我正在尝试添加与现有硬币的关系
  • 你能分享那些表币、余额和用户的架构
  • 在编辑中添加,用户更复杂,因为它是 asp 用户,但是没有问题,因为当我尝试{"title":"test", "amount":"50"} 时添加了它,我从 user_manager 上下文中得到它,一切都很好,问题是我不知道如何发送硬币 ID
  • 尝试使用这个{ "title":"test", "amount":"50", "coinid":9 },前提是数据库中存在硬币ID,因为它可能是外键

标签: c# .net .net-core


【解决方案1】:

终于弄明白了,我的模型需要像这样指定外键类型:

public class Balance
{
    public int Id { get; set; }
    public string Title { get; set; }
    public decimal Amount { get; set; }
    public int CoinId { get; set; }
    [ForeignKey("CoinId")]
    public Coin Coin { get; set; }
    public User User { get; set; }
}

现在我可以使用了:

{ “标题”:“测试”, “金额”:“50”, “硬币”:9 }

对于其他想知道的人

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2020-04-11
    • 2017-11-07
    • 1970-01-01
    • 1970-01-01
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多