【发布时间】:2017-03-02 08:47:00
【问题描述】:
我在 Asp.net Core 中使用了 EF,但尝试更新时出现以下错误。
“System.InvalidOperationException”类型的异常发生在 Microsoft.EntityFrameworkCore.dll 但未在用户代码中处理
附加信息:实体类型“TodoItem”的实例不能 被跟踪,因为此类型的另一个具有相同键的实例是 已经被追踪。添加新实体时,对于大多数键类型 如果没有设置键(即如果 键属性为其类型分配了默认值)。如果你 正在为新实体显式设置键值,确保它们不会 与现有实体或为其他生成的临时值发生冲突 新实体。附加现有实体时,确保只有一个 具有给定键值的实体实例附加到上下文。
这是我的更新代码:
public class TodoRepository : ITodoRepository
{
private readonly TodoContext _context;
public TodoRepository(TodoContext context)
{
_context = context;
//initialize database
Add(new TodoItem { Name = "Item1" });
//Add(new TodoItem { Name = "Item2" });
//Add(new TodoItem { Name = "Item3" });
}
public IEnumerable<TodoItem> GetAll()
{
return _context.TodoItems.AsNoTracking().ToList();
}
public void Add(TodoItem item)
{
_context.TodoItems.Add(item);
_context.SaveChanges();
}
public TodoItem Find(long key)
{
return _context.TodoItems.AsNoTracking().FirstOrDefault(t => t.Key == key);
}
public void Remove(long key)
{
var entity = _context.TodoItems.AsNoTracking().First(t => t.Key == key);
_context.TodoItems.Remove(entity);
_context.SaveChanges();
}
public void Update(TodoItem item)
{
_context.TodoItems.Update(item);
_context.SaveChanges();
}
}
如你所见,我已经尝试过 AsNoTracking,我也在 Startup.cs 中尝试过。
public void ConfigureServices(IServiceCollection services)
{
//inject repository into DI container, use database in memory
services.AddDbContext<TodoContext>(options => options.UseInMemoryDatabase().UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking));
//inject repository into DI container, and use sql databse
//services.AddDbContext<TodoContext>(options=>options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"]));
//The first generic type represents the type (typically an interface) that will be requested from the container.
//The second generic type represents the concrete type that will be instantiated by the container and used to fulfill such requests.
services.AddSingleton<ITodoRepository, TodoRepository>();
//add mvc service to container, this is conventional routing
//This also applys to web api which is Attribute Routing
services.AddMvc();
}
任何帮助将不胜感激。
【问题讨论】:
-
再更新一次,如果我将 TodoContext todoContext 注入到我的控制器中,并使用`_todoContext.TodoItems.Update(todoItem); _todoContext.SaveChanges(); `,它有效。我不知道为什么它在我的 TodoRepository 下不起作用。
-
你试过改变数据库入口状态吗?第 44 行github.com/hherzl/Northwind/blob/master/SourceCode/…
-
你在内存中工作吗? Todoitem.Key 的值是如何生成的? InMemory 没有任何序列支持,因此如果您没有将它们分配到任何地方,您的所有 TodoItems 都带有 Key==0。
标签: asp.net-core-mvc entity-framework-core