簡體   English   中英

該操作無法完成,因為DbContext已被處置

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

我正在嘗試向數據庫中添加一個填充了值的模型實例,但它向我顯示錯誤

“因為DbContext已被處置,所以操作無法完成。”

這是我的代碼

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

    }

錯誤例外彈出窗口出現在執行此行

db.FixerIOs.Add(FixerIOInstance);

和我的DbContext聲明在timerHandlerFixerIO方法之外,例如

private ApplicationDbContext db = new ApplicationDbContext();

您可以通過這種方式再次使用DbContext

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM