问题:
- try
- {
- string fileId = context.NewsT.Where(t => t.Id == Model.Id).FirstOrDefault().FileId;
- string filePath = context.FilesT.Where(t => t.Id == fileId).FirstOrDefault().Filepath;
- var file = context.FilesT.FirstOrDefault(m => m.Id == fileId);
- context.NewsT.Remove(Model);
- context.FilesT.Remove(file);
- var i = context.SaveChanges();
- // 删除文件
- FilesHelper.DeleteFiles(ConfigHelper.GetSectionValue("filePath") + filePath);
- result.ErrorCode = "1";
- result.Message = "API 调用成功";
- httpResponseMessage.StatusCode = HttpStatusCode.OK;
- }
- catch (Exception e)
- {
- result.ErrorCode = "-999";
- result.Message = e.Message;
- httpResponseMessage.StatusCode = HttpStatusCode.InternalServerError;
- }
- ERROR:Attaching an entity of type 'Entity.TableClass' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.
原因: 主键冲突了
解决方案:
将 string fileId = context.NewsT.Where(t => t.Id == Model.Id).FirstOrDefault().FileId; 修改为 string fileId = context.NewsT.AsNoTracking().Where(t => t.Id == Model.Id).FirstOrDefault().FileId;//AsNoTracking 是预加载, 因为 ef 本身是懒加载 (延迟加载), 所以如果这里不用预加载, 到执行修改时会报 model.id 冲突错误, 所以要用预加载
来源: http://www.bubuko.com/infodetail-3008145.html