我正在尝试将填充了值的模型实例添加到数据库,但它显示错误
“由于已经处理了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();
答案 0 :(得分:3)
您可以这样再次使用DbContext
using(var db = new ApplicationDbContext())
{
db.FixerIOs.Add(FixerIOInstance);
await db.SaveChangesAsync();
}