I'm accessing my db instance via dependency injection, which is scoped to the request.
Here's the code from my startup.cs
:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("ApiEntity"));
options.EnableSensitiveDataLogging(true);
});
services.AddRazorPages();
}
In my index.cshtml.cs
file, I have a list of projects that I want to update. I'm binding them to the PageModel like so:
[BindProperty]
public List<Project> Projects { get; set; }
When the OnPost
method is called with the updated entities and I run _context.SaveChanges();
the tracked entities do not get updated.
When I try updating the entities first by calling: _context.UpdateRange(Projects);
I get the following error:
InvalidOperationException: The instance of entity type 'Project' cannot be tracked because another instance with the same key value for {'ProjectId'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values
I've looked at other examples of this error messages and the solution seems to be to scope your repository (which I already am) or to detach your entity and then reattach it but I'm not sure why I would add this additional complexity. I should be able to update the entities that are being tracked by simply calling _context.saveChanges
. Is this possible ? If so, what am I doing wrong ?