Search code examples
entity-frameworkasp.net-web-apiodataasp.net-web-api2

How to post to a related collection in odata webapi


I've found this answer which helped me to set a route, but I'm having a problem adding entity to a related collection.

Models:

public class Book
{
    public int BookId { get; set; }
    public string Title { get; set; } and so on

    [ForeignKey("AuthorId")]
    public ICollection<Author> Authors { get; set; }
}

public class Author
{
    public int AuthorId { get; set; }
    public string Name { get; set; }

    [ForeignKey("BookId")] 
    public ICollection<Book> Books { get; set; }
}

Controller method for posting to a related collection:

    [ODataRoute("Books({key})/Authors")]
    public async Task<IHttpActionResult> PostAuthor([FromODataUri] int key, Author author)
    {
        var book = await db.Books.FindAsync(key);
        if (book == null)
        {
            return NotFound();
        }
        book.Authors.Add(author);

        await db.SaveChangesAsync();
        return StatusCode(HttpStatusCode.NoContent);
    }

I can see that Author is sent through, but book.Authors is null and you can't add to it. link to image


Solution

  • Find won't bring back children. Try:

    var book = await db.Books
                        .Include(b => b.Authors)
                        .FirstOrDefaultAsync(b => b.BookId == key);
    

    Load related entities