【问题标题】:How to post to a related collection in odata webapi如何发布到 odata webapi 中的相关集合
【发布时间】:2016-05-23 00:45:54
【问题描述】:

我找到了这个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);
    }

我可以看到 Author 是通过发送的,但是 book.Authors 是 null 并且您不能添加到它。 link to image

【问题讨论】:

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


    【解决方案1】:

    Find 不会带回孩子。试试:

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

    Load related entities

    【讨论】:

    • 是的,抱歉打错了 - 使用 FirstOrDefault 时不需要 Where()。
    • 我用我的解决方案编辑了您的答案,以便我可以接受。你的回答是最接近回答的,但它在 VS 中给出了错误。
    猜你喜欢
    • 2015-02-14
    • 2013-01-17
    • 1970-01-01
    • 2020-02-04
    • 2014-03-31
    • 1970-01-01
    • 1970-01-01
    • 2015-06-21
    • 2014-03-01
    相关资源
    最近更新 更多