如果商品与货柜存在外键,比如:
public class Good{ public long id{ get; set; } public string name{get;set;} public long CabinetId { get; set; } public Cabinet Cabinet { get; set; } } public class cabinet{ public long id{get;set;} public string name{get;set;} public List<good> list=new List<good>(); }
在修改某一商品记录时,可能存在2个坑,注意一下:
1、第一个坑,如果修改如下:
public async Task<IActionResult> AddGrid(Grid grid) { 。。。 var modGrid=db.Grids.SingleOrDefault(x => x.Id == grid.Id); if (modGrid == null) { return Content("修改失败!原因:记录不存在"); } db.Update(grid); await db.SaveChangesAsync(); }
在执行上面代码 时会报错
The instance of entity type ‘***‘ cannot be tracked because another instance with the same key value for {‘ID‘} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using ‘***’ to see the conflicting key values.
解决办法 :modGrid查找时不要跟踪
var modGrid=db.Grids.AsNoTracking().SingleOrDefault(x => x.Id == grid.Id);
2、第二个坑,按上面修改成功后发现,外键怎么修改都不成功,也就是明明修改了外键值,但浏览时发现还是没有变,原来在controller获取商品grid时,系统已自动映射了外键类Cabinet,这时虽然CabinetId值时修改了,但Cabinet还是原因的,所以save后还没有改变。
解决办法:让Cabinet=null,再save就Ok了
grid.Cabinet = null; db.Update(grid);