再次调用上下文类清除嵌套列表

时间:2019-01-19 18:41:16

标签: c# api asp.net-core

嘿,我的结构看起来像这样: enter image description here

这是2个图书馆,里面有一些数据,还有一本叫做“书”的书的清单。

在我的库控制器中,我使用诸如

的模拟数据填充上下文
public LibrariesController(LibrariesContext context)
    {
        _context = context;

        if (_context.Libraries.Count() == 0)
        {
            // Create a new TodoItem if collection is empty,
            // which means you can't delete all TodoItems.
            _context.AddRange(getMockedLibraries());

            _context.SaveChanges();
        }
    }

用于模拟数据的方法仅向该上下文添加一些静态内容,例如:

private List<Book> getMockedBooks()
    {
        List<Book> mockedBooks = new List<Book>();

        Book newBook = new Book();
        newBook.Title = "Pride and Prejudice (Paperback)";
        newBook.Author = "Jane Austen";

        mockedBooks.Add(newBook);

        newBook = new Book();
        newBook.Title = "To Kill a Mockingbird (Paperback)";
        newBook.Author = "Harper Lee";

        mockedBooks.Add(newBook);

        return mockedBooks;
    }

    private List<Library> getMockedLibraries()
    {

        List<Library> mockedLibraries = new List<Library>();



        Library newLibrary = new Library();

        newLibrary.Name = "ZUT Library";
        newLibrary.ImgSrc = "http://przemysl-40.pl/wp-content/uploads/logo_ZUT.jpg";
        newLibrary.Books = getMockedBooks();

        mockedLibraries.Add(newLibrary);

        newLibrary = new Library();

        newLibrary.Name = "US Library";
        newLibrary.ImgSrc = "http://partner.kubg.edu.ua/images/stories/Partners/poland1.jpg";
        newLibrary.Books = getMockedBooks();

        mockedLibraries.Add(newLibrary);

        return mockedLibraries;

    }

我的LibrariesContext基于DBContextOptions,并且在内部具有库DbSet:

public class LibrariesContext : DbContext
{
    public LibrariesContext(DbContextOptions<LibrariesContext> options)
        : base(options)
    {
    }

    public DbSet<Library> Libraries { get; set; }
    public DbSet<Book> Books { get; set; }
}

最有趣的部分是当我转到/ api / Libraries端点并想第二次在我的网站上看到bueatifull JSON时,实现如下所示:

// GET: api/Libraries
    [HttpGet]
    public async Task<ActionResult<IEnumerable<Library>>> GetTodoItems()
    {
        return await _context.Libraries.ToListAsync();
    }

我是.NetCore的初学者,我不明白为什么在第二次向同一个端点发出请求后,却得到了一些空值来代替书籍列表,例如:

enter image description here

我真的很感谢任何建议。

2 个答案:

答案 0 :(得分:1)

return await _context.Libraries.ToListAsync();更改为

 return await _context.Libraries.Include(x => x.Books).ToListAsync();

答案 1 :(得分:1)

在GET请求中,您的查询仅返回库。尝试eager loading书籍,以便将它们加入查询并包含在结果中:

// GET: api/Libraries 
[HttpGet] 
public async Task<ActionResult<IEnumerable<Library>>> GetTodoItems() 
{ 
    return await _context.Libraries.Include(l => l.Books).ToListAsync(); 
}