3

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

1 Answer 1

1

Find won't bring back children. Try:

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

Load related entities

2
  • Yes, sorry had a typo - you don't need a Where() when using FirstOrDefault. May 23, 2016 at 15:10
  • I edited your answer with my sollution so that I can accept it. Your anwer was the closest to answering it, but it gave an error in VS.
    – kolbanis
    May 23, 2016 at 15:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.