Gerald Gonzales
Gerald Gonzales

Reputation: 533

Asynchronous method with context dispose

I have the following code below:

public Task<Service> GetSomething()
{
    using (var myContext = new DbContext())
    {
        var returnObj = (from rp in myContext.Services1
                        join op in myContext.Services2 on rp .Id equals op.ServiceId into g
                        join ep in myContext.Services3 on rp .Id equals ep.ServiceId
                        from n in g.DefaultIfEmpty()
                        where rp.Name == code
                        select rp).FirstOrDefaultAsync();

        return returnObj;
    }
}

Now this is working and I am encountering error:

The operation cannot be completed because the DbContext has been disposed.

After reading, looks like FirstOrDefaultAsync is a deffered execution and I need to convert it to list first for it to be concrete.

How am I gonna convert the result of this query because I tried .ToListAsync() but it doesn't have any FirstOrDefault after it anymore.

Upvotes: 6

Views: 7344

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34189

In your case, EF6 Async operation is called and its task is returned to original caller. Then, DbContext is immediatelly disposed without waiting for completion.
It is an incorrect usage of async/await functionality.

You need to await the result before disposing your context:

public async Task<YourEntity> GetYourEntity()
{
  using (var myContext = new DbContext())
  {
    var returnObj = (from rp in myContext.Services1
                     join op in myContext.Services2 on rp .Id equals op.ServiceId into g
                     join ep in myContext.Services3 on rp .Id equals ep.ServiceId
                     from n in g.DefaultIfEmpty()
                     where rp.Name == code
                     select rp).FirstOrDefaultAsync();

    //return returnObj; // returns Task, wrong!
    return await returnObj; // returns result, right!
  }
}

This way, it will wait for operation to complete and then dispose myContext.

Upvotes: 5

Related Questions