当前位置:   article > 正文

Entity Framework操作数据库失败解决方法(持续更新)_microsoft.entityframeworkcore 引用不成功

microsoft.entityframeworkcore 引用不成功
今天用EF来删除数据的时候提示:
The object cannot be deleted because it was not found in the ObjectStateManager.

之后再网上找到了解决方法(附上链接:https://stackoverflow.com/questions/15945172/the-object-cannot-be-deleted-because-it-was-not-found-in-the-objectstatemanager)


上面的红线框中的数据上下文是不同的对象,导致了出错;

最后更改为同一个数据库上下文类就行了

如下图


2018-03-28更新:

情景描述:当我在使用web api来对数据修改的时候,而在使用过程中提示如下错误:

exceptionMessage:"Attaching an entity of type 'FruitShoppingSystem.Models.Business' 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."
exceptionType:"System.InvalidOperationException"

message:"An error has occurred."

后面发现了也是之前获取到的数据没有进行更改而更改了传入的数据才出错的:

错误之前的代码如下:


更改之后如下:修改之后就没问题了

  1.         public async Task<IHttpActionResult> PutBusiness(Guid id, Business business)
  2.         {
  3.             if (!ModelState.IsValid)
  4.             {
  5.                 return Ok(status.GetResult("No", "数据验证失败!"));
  6.             }
  7.             if (id != business.Id)
  8.             {
  9.                 return Ok(status.GetResult("No", "所选商家不存在!"));
  10.             }
  11.             var b = await businessRepository.Get(id);
  12.             b.Email = business.Email;
  13.             b.Address = business.Address;
  14.             b.PhoneNumber = business.PhoneNumber;
  15.             b.Person = business.Person;
  16.             b.Name = business.Name;
  17.             try
  18.             {
  19.                 await businessRepository.Update(b);
  20.             }
  21.             catch (DbUpdateConcurrencyException ex)
  22.             {
  23.                 if (!BusinessExists(id))
  24.                 {
  25.                     return Ok(status.GetResult("No", "所选商家不存在,错误信息为:" + ex.Message));
  26.                 }
  27.                 else
  28.                 {
  29.                     return Ok(status.GetResult("No", "发生异常,异常信息为:" + ex.Message));
  30.                 }
  31.             }
  32.             return Ok(status.GetResult("Ok", "修改商家信息成功!"));
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/856313
推荐阅读
相关标签
  

闽ICP备14008679号