由于DbContext已被处置异常,因此无法完成操作

时间:2016-10-12 07:45:42

标签: c# asp.net asp.net-mvc entity-framework dbcontext

我正在尝试将填充了值的模型实例添加到数据库,但它显示错误

  

“由于已经处理了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();

1 个答案:

答案 0 :(得分:3)

您可以这样再次使用DbContext

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