Asynchronous method with context dispose

Viewed 4752

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.

1 Answers
Related