我找到了这个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; }
}
用于发布到相关集合的 Controller 方法:
[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
最佳答案
查找不会带回孩子。尝试:
var book = await db.Books
.Include(b => b.Authors)
.FirstOrDefaultAsync(b => b.BookId == key);
Load related entities