如何在odata webapi中发布相关集合

时间:2016-05-23 00:45:54

标签: entity-framework asp.net-web-api odata asp.net-web-api2

我发现这个answer帮助我设置了一条路线,但是我在向相关集合添加实体时遇到了问题。

型号:

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

发布到相关集合的控制器方法:

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

我可以看到作者已发送,但是book.Authors为空,您无法添加。 link to image

1 个答案:

答案 0 :(得分:1)

发现不会带回孩子。尝试:

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

Load related entities