文章内容

2017/12/24 16:56:39,作 者: 黄兵

entity framework中 已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭

最近要用Entity Framework更新数据,代码如下:

using (UnitOfWork uow = new UnitOfWork())
{
var ZhiHuAll = uow.ZhiHuExtendRepository.GetAll();
foreach (var item in ZhiHuAll)
{
string newFileName = Guid.NewGuid() + Path.GetExtension(item.ImageUrl);
//如果目录不存在就新建一个
CreateDirectory ImgDr = new CreateDirectory();
ImgDr.CreatePath(FilePath);
await Client.DownloadFileTaskAsync(item.ImageUrl, FilePath + newFileName);

Zhihu_Extend ZhihuExtend = new Zhihu_Extend();
ZhihuExtend.Image_source = item.Image_source;
ZhihuExtend.ImageUrl = newFileName;
ZhihuExtend.Js_Url = item.Js_Url;
ZhihuExtend.Css_Url = item.Css_Url;
ZhihuExtend.Share_Url = item.Share_Url;
uow.ZhiHuExtendRepository.Update(ZhihuExtend);
uow.SaveChanges();
}
}

运行代码报如下错误:

entity framework中 已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭

解决方案:

using (UnitOfWork uow = new UnitOfWork())
{
var ZhiHuAll = uow.ZhiHuExtendRepository.GetAll();
foreach (var item in ZhiHuAll.ToList())
{
string newFileName = Guid.NewGuid() + Path.GetExtension(item.ImageUrl);
//如果目录不存在就新建一个
CreateDirectory ImgDr = new CreateDirectory();
ImgDr.CreatePath(FilePath);
await Client.DownloadFileTaskAsync(item.ImageUrl, FilePath + newFileName);

Zhihu_Extend ZhihuExtend = new Zhihu_Extend();
ZhihuExtend.Image_source = item.Image_source;
ZhihuExtend.ImageUrl = newFileName;
ZhihuExtend.Js_Url = item.Js_Url;
ZhihuExtend.Css_Url = item.Css_Url;
ZhihuExtend.Share_Url = item.Share_Url;
uow.ZhiHuExtendRepository.Update(ZhihuExtend);
uow.SaveChanges();
}
}

注意上面的ToList()。

参考资料:entity framework中 已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭

黄兵个人博客原创。

转载请注明出处:黄兵个人博客 - entity framework中 已有打开的与此 Command 相关联的 DataReader,必须首先将它关闭

分享到:

发表评论

评论列表