这里记录一个在使用.net core中ef core执行数据库操作时遇到的问题:

我在代码中使用DbContext下的Update方法准备将更改后的数据像这样步到数据库:

_context.Menus.Update(menu);

这是很常见的用法,但没想到一直报如下错误:

The instance of entity type 'Menu' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.

使用谷歌翻译翻译为:

无法跟踪实体类型“Menus”的实例,因为已经跟踪了具有相同键值的{'Id'}的另一个实例。

我的代码如下:

 if (!menu.OrderNumber.HasValue)
{
var maxOrderItem =
_context.Menus.Where(x => x.ParentId == menu.ParentId)
.OrderByDescending(x => x.OrderNumber)
.FirstOrDefault();
menu.OrderNumber = maxOrderItem != null ? maxOrderItem.OrderNumber + : ;
}
///EF core中没有AddOrUpdate方法,所以针对是新增菜单还是修改菜单做出判断
if (isNewMenu)
{
_context.Menus.Add(menu);
}
else
{
_context.Menus.Update(menu);///此处报出上述异常
}
_context.SaveChanges();

我通过百度,发现国内网站上没有出现类似错误的记载,最后,我在stackoverflow上看到一段类似问题描述:

该用户描述,他进行了如下尝试:

在使用_context获取值时,使用AsNoTracking()方法,我进行尝试,修改我的代码如下:

if (!menu.OrderNumber.HasValue)
{
var maxOrderItem =
_context.Menus.AsNoTracking().Where(x => x.ParentId == menu.ParentId)
.OrderByDescending(x => x.OrderNumber)
.FirstOrDefault();
menu.OrderNumber = maxOrderItem != null ? maxOrderItem.OrderNumber + : ;
}
///EF core中没有AddOrUpdate方法,所以针对是新增菜单还是修改菜单做出判断
if (isNewMenu)
{
_context.Menus.Add(menu);
}
else
{
_context.Menus.Update(menu);
}
_context.SaveChanges();

发现我遇到的这个问题得以圆满解决。

我在这里记录一下这个问题,但其中的道理我没有深究,就不说了。

The instance of entity type 'Menu' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.的更多相关文章

  1. The instance of entity type 'xxxx' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked.

    一.问题描述 问题:The instance of entity type 'xxxx' cannot be tracked because another instance with the sam ...

  2. EF 更新实体 The instance of entity type 'BabyEvent' cannot be tracked because another instance

    加上AsNoTracking. 人不能两次踏入同一条河. 我 就踏入了.o(╥﹏╥)o

  3. The instance of entity type 'manager' 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 ent

    最近在用ASP.NET CORE时遇到一些问题,现记录下: 出现上述错误,即在更新实体数据时出现的错误 services.AddDbContext<StoreContext>(c => ...

  4. [转] EF cannot be tracked because another instance of this type with the same key is already being tracked

    本文转自:http://stackoverflow.com/questions/6033638/an-object-with-the-same-key-already-exists-in-the-ob ...

  5. type parameters of <T>T cannot be determined; no unique maximal instance exists for type variable T with upper bounds int,java.lang.Object

    今天在进行代码检查的时候出现下面的异常: type parameters of <T>T cannot be determined; no unique maximal instance ...

  6. The entity type XXX is not part of the model for the current context.

    今天遇到了一个奇葩问题,虽然解决了,但还是一脸懵,先附赠一下别人的解决方案:https://www.cnblogs.com/zwjaaron/archive/2012/06/08/2541430.ht ...

  7. Flask - 访问返回字典的接口报错:The view function did not return a valid response. The return type must be a string, tuple, Response instance, or WSGI callable, but it was a dict.

    背景 有一个 Flask 项目,然后有一个路由返回的是 dict 通过浏览器访问,结果报错 关键报错信息 TypeError: 'dict' object is not callable The vi ...

  8. Entity Framework 6如何进行导航属性的筛选(context.Msg.First(t=>t.Id==1).Include(t=>t.MsgDetail),筛选MsgDetail带条件)

    问题: https://q.cnblogs.com/q/98333/ Msg表(Id,Content,IsDel).内有 virtual ICollection<MsgDetail> Ms ...

  9. The entity type <type> is not part of the model for the current context

    这是在网站里遇到的一个错误,自动生成的不能手动添加, reference: http://stackoverflow.com/questions/19695545/the-entity-type-xx ...

随机推荐

  1. mysql查询表大小

    工作中常用命令参考,收集如下: 查询表大小:select table_name, data_length from information_schema.tables where table_sche ...

  2. JMETER 使用断言

    断言概念 断言就是在执行某个请求后,根据返回的结果,判断返回是否正确,如果不正确,则表示事务失败. 添加断言 启动流程时返回的数据是一个 json对象,结构为 {success:true,msg:&q ...

  3. Linux shell case条件判断及位置变量

    case语句使用于需要进行多重分支的应用情况 case分支判断结构 语法: case 变量名称 in      value1)          statement          statemen ...

  4. [转]【Servlet】Servlet的访问过程

    创建时间:6.15 Servlet的访问过程 1. 画图描述整个访问过程: *每次访问service()方法都会创建一对新的request和response对象,都不一样 2. 访问过程2: 问题:对 ...

  5. 【HTTP】HTTP协议的请求与响应

    创建时间:6.14 http协议 的位置 1.HTTP是什么 超文本传输协议(HyperText Transfer Protocol) 2.Http协议的组成 Http协议由Http请求和Http响应 ...

  6. leetcode4 Median of Two Sorted Arrays学习记录

    学习了扁扁熊的题解:https://leetcode-cn.com/problems/median-of-two-sorted-arrays/solution/4-xun-zhao-liang-ge- ...

  7. Codeforces G. The Brand New Function(枚举)

    题目描述: The Brand New Function time limit per test 2 seconds memory limit per test 256 megabytes input ...

  8. WTL 9.0的变化 - atlcrack.h

    atlcrack.h中是一些对消息映射的简化,9.0版本中只增加了一个WM_MOUSEWHEEL的响应,而且要求windows vista. #if (_WIN32_WINNT >= 0x060 ...

  9. SpringBoot——IDEA使用 Spring Initializer快速创建项目【四】

    前言 使用Spring Initializer快速创建项目 步骤 首先肯定是打开我们的IDEA的编辑器呀~ 创建项目 File -> New -> Project Spring Initi ...

  10. 07-cmake语法-MATCHES

    如果给定的字串或变量值域给定的正则表达式匹配的话,表达式返回真. IF (CMAKE_SYSTEM_NAME MATCHES "Linux") MESSAGE(STATUS &qu ...