我在Asp.net Core中使用了EF,但在嘗試更新時遇到了以下錯誤。
Microsoft.EntityFrameworkCore.dll中出現“System.InvalidOperationException”類型的異常,但未在用戶代碼中處理
附加信息:無法跟踪實體類型“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();
}
任何幫助,將不勝感激。
我通過將services.AddDbContext更改為services.AddScoped解決了這個問題,這已在下面的鏈接中指出。 https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection