Ali Jamal Ali Jamal - 1 month ago 18
ASP.NET (C#) Question

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

Salaamun Alekum

I am trying to adding 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 where I am adding values where exception appears

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



Thank You

Answer

You can use DbContext again this way

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