Nested list is cleared out with second call to context class












-1















Hey I have structure which looks like this:
enter image description here



Those are 2 libraries which have some data inside and also list of books called "books".



Inside of my Library controller I'm filling context with mocked data like:



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


Methods for mocking data just add some static content to this context like:



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;

}


My LibrariesContext is based on DBContextOptions and has Libraries DbSet inside:



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

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


The funniest part happen when I go to the /api/Libraries endpoint and want to see bueatifull JSON on my site second time, implementation looks like:



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


I'm a beginner with a .NetCore and I can't understand why after second request to the same endpoint I got some nulls in place of books list like:



enter image description here



I would be really grateful for any advice.










share|improve this question























  • It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

    – Charleh
    Jan 19 at 18:57


















-1















Hey I have structure which looks like this:
enter image description here



Those are 2 libraries which have some data inside and also list of books called "books".



Inside of my Library controller I'm filling context with mocked data like:



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


Methods for mocking data just add some static content to this context like:



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;

}


My LibrariesContext is based on DBContextOptions and has Libraries DbSet inside:



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

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


The funniest part happen when I go to the /api/Libraries endpoint and want to see bueatifull JSON on my site second time, implementation looks like:



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


I'm a beginner with a .NetCore and I can't understand why after second request to the same endpoint I got some nulls in place of books list like:



enter image description here



I would be really grateful for any advice.










share|improve this question























  • It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

    – Charleh
    Jan 19 at 18:57
















-1












-1








-1








Hey I have structure which looks like this:
enter image description here



Those are 2 libraries which have some data inside and also list of books called "books".



Inside of my Library controller I'm filling context with mocked data like:



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


Methods for mocking data just add some static content to this context like:



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;

}


My LibrariesContext is based on DBContextOptions and has Libraries DbSet inside:



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

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


The funniest part happen when I go to the /api/Libraries endpoint and want to see bueatifull JSON on my site second time, implementation looks like:



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


I'm a beginner with a .NetCore and I can't understand why after second request to the same endpoint I got some nulls in place of books list like:



enter image description here



I would be really grateful for any advice.










share|improve this question














Hey I have structure which looks like this:
enter image description here



Those are 2 libraries which have some data inside and also list of books called "books".



Inside of my Library controller I'm filling context with mocked data like:



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


Methods for mocking data just add some static content to this context like:



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;

}


My LibrariesContext is based on DBContextOptions and has Libraries DbSet inside:



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

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


The funniest part happen when I go to the /api/Libraries endpoint and want to see bueatifull JSON on my site second time, implementation looks like:



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


I'm a beginner with a .NetCore and I can't understand why after second request to the same endpoint I got some nulls in place of books list like:



enter image description here



I would be really grateful for any advice.







c# api asp.net-core






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 19 at 18:41









Patryk JanikPatryk Janik

14318




14318













  • It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

    – Charleh
    Jan 19 at 18:57





















  • It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

    – Charleh
    Jan 19 at 18:57



















It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

– Charleh
Jan 19 at 18:57







It's probably a race condition, something along the lines of your first request taking longer because .net is doing some extra stuff with the db context, this means by the time it evaluates your context some of the properties might have lazy loaded. Just a guess, but definitely eager loading is the solution.

– Charleh
Jan 19 at 18:57














2 Answers
2






active

oldest

votes


















1














In your GET request, your query is only returning Libraries. Try eager loading the Books so that they are joined in the query and included in the results:



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





share|improve this answer
























  • What a strange requirement.

    – Patryk Janik
    Jan 19 at 19:25



















1














change return await _context.Libraries.ToListAsync(); to



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





share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270227%2fnested-list-is-cleared-out-with-second-call-to-context-class%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    In your GET request, your query is only returning Libraries. Try eager loading the Books so that they are joined in the query and included in the results:



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





    share|improve this answer
























    • What a strange requirement.

      – Patryk Janik
      Jan 19 at 19:25
















    1














    In your GET request, your query is only returning Libraries. Try eager loading the Books so that they are joined in the query and included in the results:



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





    share|improve this answer
























    • What a strange requirement.

      – Patryk Janik
      Jan 19 at 19:25














    1












    1








    1







    In your GET request, your query is only returning Libraries. Try eager loading the Books so that they are joined in the query and included in the results:



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





    share|improve this answer













    In your GET request, your query is only returning Libraries. Try eager loading the Books so that they are joined in the query and included in the results:



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






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 19 at 18:49









    devNulldevNull

    55047




    55047













    • What a strange requirement.

      – Patryk Janik
      Jan 19 at 19:25



















    • What a strange requirement.

      – Patryk Janik
      Jan 19 at 19:25

















    What a strange requirement.

    – Patryk Janik
    Jan 19 at 19:25





    What a strange requirement.

    – Patryk Janik
    Jan 19 at 19:25













    1














    change return await _context.Libraries.ToListAsync(); to



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





    share|improve this answer




























      1














      change return await _context.Libraries.ToListAsync(); to



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





      share|improve this answer


























        1












        1








        1







        change return await _context.Libraries.ToListAsync(); to



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





        share|improve this answer













        change return await _context.Libraries.ToListAsync(); to



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






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 19 at 18:48









        SimonareSimonare

        11.5k11737




        11.5k11737






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270227%2fnested-list-is-cleared-out-with-second-call-to-context-class%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Homophylophilia

            Updating UILabel text programmatically using a function

            Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage