我找到了这个 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);
}
我可以看到 Author 已发送,但 book.Authors 为 null,您无法添加。 link to image
最佳答案
寻找不会带回 child 。尝试:
var book = await db.Books
.Include(b => b.Authors)
.FirstOrDefaultAsync(b => b.BookId == key);
关于entity-framework - 如何发布到 odata webapi 中的相关集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37381165/