0

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 ?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Frosty619
  • 1,381
  • 4
  • 23
  • 33

1 Answers1

0

Alright, I figured it out. I'm keeping this up for other weary developers:

In my cshtml.cs file, I was assigning Projects in the constructor function:

    public ProjectsPageModel(AppDbContext _context)
    {
        this._context = _context;
        Projects = _context.Projects.ToList();
    }

When I removed the db call from the constructor function and put the call in the OnGet method instead, I was able to successfully update the db by:

         _context.UpdateRange(Projects);
         _context.SaveChanges();
Frosty619
  • 1,381
  • 4
  • 23
  • 33