我在Asp.net Core中使用了EF,但是在嘗試更新時出現了錯誤。Asp.net核心EF更新
「System.InvalidOperationException」類型發生在 Microsoft.EntityFrameworkCore.dll但在用戶代碼
附加信息沒有處理的一個例外:實體類型「的TodoItem」的實例不能被 因爲跟蹤具有相同密鑰的這種類型的另一個實例是 已被跟蹤。添加新實體時,對於大多數密鑰類型,如果未設置任何密鑰(即,如果 key屬性被指定爲其類型的默認值),則將創建一個 唯一臨時密鑰值。如果您爲 明確設置新實體的關鍵值,請確保它們不與 與現有實體衝突或爲其他 新實體生成的臨時值衝突。在附加現有實體時,請確保只有一個具有給定鍵值的實體實例附加到上下文。
這是我的更新代碼:
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行https://github.com/hherzl/Northwind/blob/master/SourceCode/Northwind.Core/DataLayer/Repository.cs –
你正在記憶中工作?如何生成Todoitem.Key的值? InMemory沒有任何序列支持,所以如果你不把它們分配到任何地方,所有你的TodoItems都帶有Key == 0。 – Dmitry