如何使用外键在.net core 2 web api中发帖

时间:2018-03-20 05:34:01

标签: c# .net .net-core

我有现有型号:

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 }
}

但是我总是得到一个null对象异常或者将foreignkey id设置为null的插入,我试着环顾四周但是找不到任何东西,我对.net和看起来相对较新求救,谢谢!

修改

数据库结构:

database structure

1 个答案:

答案 0 :(得分:0)

最后想通了,我的模型需要指定一个外键类型:

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”, “coinid”:9 }

对于其他想知道的人