简体   繁体   中英

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

I am trying to add a model instance filled with values to database but it is showing me error

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

Here is my code

private async void timerHandlerFixerIO(object sender, EventArgs e)
    {
        string html = string.Empty;
        string url = @"http://api.fixer.io/latest";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.AutomaticDecompression = DecompressionMethods.GZip;

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        using (Stream stream = response.GetResponseStream())
        using (StreamReader reader = new StreamReader(stream))
        {
            html = reader.ReadToEnd();
        }

        Debug.WriteLine(html);
        FixerIO FixerIOInstance = new FixerIO();
        FixerIOInstance.rates = new rates();
        FixerIOInstance = JsonConvert.DeserializeObject<FixerIO>(html);
        db.FixerIOs.Add(FixerIOInstance);
        await db.SaveChangesAsync();

    }

Error exception popup appear on executing this line

db.FixerIOs.Add(FixerIOInstance);

and my DbContext declaration outside the timerHandlerFixerIO method like

private ApplicationDbContext db = new ApplicationDbContext();

You can use DbContext again this way

using(var db = new ApplicationDbContext())
{
   db.FixerIOs.Add(FixerIOInstance);
   await db.SaveChangesAsync();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM