Amirgem
Amirgem

Reputation: 161

How to do a post in .net core 2 web api with foreign keys

I have the current models:

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

And the following method to post:

    [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"));
    }

I tried multiple JSON formats to post the information:

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

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

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

But I always get either a null object exception or an insert with the foreignkey id set to null, I tried looking around but can't find anything on it, I'm relatively new to .net and looking for help, thank you!

EDIT:

DB Structure:

database structure

Upvotes: 1

Views: 1751

Answers (1)

Amirgem
Amirgem

Reputation: 161

Finally figured it out, my models NEED to specify a foreign key type like so:

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

And now I can use:

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

For anyone else wondering

Upvotes: 2

Related Questions