赞
踩
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."
后面发现了也是之前获取到的数据没有进行更改而更改了传入的数据才出错的:
错误之前的代码如下:
更改之后如下:修改之后就没问题了
- public async Task<IHttpActionResult> PutBusiness(Guid id, Business business)
- {
- if (!ModelState.IsValid)
- {
- return Ok(status.GetResult("No", "数据验证失败!"));
- }
-
- if (id != business.Id)
- {
- return Ok(status.GetResult("No", "所选商家不存在!"));
- }
-
- var b = await businessRepository.Get(id);
- b.Email = business.Email;
- b.Address = business.Address;
- b.PhoneNumber = business.PhoneNumber;
- b.Person = business.Person;
- b.Name = business.Name;
-
- try
- {
- await businessRepository.Update(b);
- }
- catch (DbUpdateConcurrencyException ex)
- {
- if (!BusinessExists(id))
- {
- return Ok(status.GetResult("No", "所选商家不存在,错误信息为:" + ex.Message));
- }
- else
- {
- return Ok(status.GetResult("No", "发生异常,异常信息为:" + ex.Message));
- }
- }
-
- return Ok(status.GetResult("Ok", "修改商家信息成功!"));
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。