0

So I have two tables: Recipe and Step. One recipe contains multiple Steps.

I have a WPF application and when I load a specific view, I want to asynchronously load data using Entity Framework. So I have this function

public async Task<List<recipe>> GetRecipeAsync()
{
    using (var context = new RecipeSystem())
    {
        return await context.recipe.ToListAsync();
    }
}

In the constructor of my class, I am calling the function above like this:

Recipes = _recipeService.GetRecipeAsync().Result;

But for some reason, I get an ObjectDisposedException.

Exception

If I set a breakpoint in GetRecipeAsync() and check what value context.recipe.ToListAsync() has, it looks fine. Step is available there.

user2877820
  • 287
  • 4
  • 19

1 Answers1

1

A related Step object cannot be lazily loaded after the context has been disposed. You could try to load the related entities up front using eager loading:

public async Task<List<recipe>> GetRecipeAsync()
{
    using (var context = new RecipeSystem())
    {
        return await context.recipe.Include(x => x.Steps).ToListAsync().ConfigureAwait(false);
    }
}

Also note that is is considered a good practice to disable the context capturing in async service methods by calling the ConfigureAwait(false) method. This may also save you from deadlocks: http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • Thanks alot. That worked perfectly so far. But how does the syntax look like if I have a 3rd table that references from steps. e.g. One recipe has multiple steps. One steps has multiple actions. – user2877820 Oct 30 '17 at 14:50
  • 1
    That's another question really but you could use another Include: https://stackoverflow.com/questions/15764572/ef-linq-include-multiple-and-nested-entities – mm8 Oct 30 '17 at 14:53