InvalidOperationException: Cannot save changes for an entity in state 'Unchanged'
File a bug
I found the following issue that seems to trigger the same exception: #28152
context.SaveChangesAsync() throws an exception when I try to update an entity with the message:
An exception occurred in the database while saving changes for context type 'Buttons.Data.ButtonContext'.
System.InvalidOperationException: Cannot save changes for an entity of type 'Button' with primary key values {Id: 1} in state 'Unchanged'. This may indicate a bug in Entity Framework, please open an issue at https://go.microsoft.com/fwlink/?linkid=2142044.
The project is a small personal project and open source. The comit where the exception is thrown can be found here: https://github.com/MilchbarBaden/Buttons/tree/bug-sqlite-update
I didn't get around to create a small repo that reproduces the error. I suspect, that the error is related to the owned entity Crop.
And it might also just be my fault and I didn't see what I did wrong yet. The project used ef core with an in-memory database previously and I am in the process of switching to a sqlite database file. The exception started occuring after the switch to sqlite.
Steps to reproduce error:
- Start application (Should open
./Button/Name) - Enter any name and click on Next (Should open
./Button/Create) - Upload any jpeg/png and click on Next (Should open
./Button/Crop/{id}) - Click next (Crashes but should open
./Button/Confirm/{id})
Include your code
DbContext
using Microsoft.EntityFrameworkCore;
public class ButtonContext : DbContext
{
public DbSet<Button> Buttons => Set<Button>();
public DbSet<Owner> Owners => Set<Owner>();
public ButtonContext(DbContextOptions<ButtonContext> dbContextOptions) : base(dbContextOptions)
{
ChangeTracker.Tracked += ChangeTrackerTracked;
ChangeTracker.StateChanged += ChangeTrackerStateChanged;
}
private void ChangeTrackerTracked(object? sender, Microsoft.EntityFrameworkCore.ChangeTracking.EntityTrackedEventArgs e)
{
if (!e.FromQuery && e.Entry.State == EntityState.Added && e.Entry.Entity is DateEntity newEntity)
{
newEntity.Created = DateTime.Now;
newEntity.LastModified = DateTime.Now;
}
}
private void ChangeTrackerStateChanged(object? sender, Microsoft.EntityFrameworkCore.ChangeTracking.EntityStateChangedEventArgs e)
{
if (e.NewState == EntityState.Modified && e.Entry.Entity is DateEntity dateEntity)
{
dateEntity.LastModified = DateTime.Now;
SaveChanges();
}
}
}
Main Entity
using Microsoft.EntityFrameworkCore;
[Index(nameof(Path), IsUnique = true)]
public class Button : DateEntity
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public string Path { get; set; } = string.Empty;
public ButtonStatus Status { get; set; }
public virtual Crop Crop { get; set; } = new Crop();
public string OwnerId { get; set; }
public virtual Owner Owner { get; set; }
public DateTime Created { get; set; }
public DateTime LastModified { get; set; }
public Button(Owner owner)
{
Owner = owner;
OwnerId = owner.Id;
}
#nullable disable
private Button() { }
#nullable restore
}
public interface DateEntity
{
DateTime Created { get; set; }
DateTime LastModified { get; set; }
}
public enum ButtonStatus { Uploaded, Confirmed, Printed }
Owned Entity
using Microsoft.EntityFrameworkCore;
[Owned]
public class Crop
{
public double ScaleX { get; set; } = 1.0;
public double ScaleY { get; set; } = 1.0;
public double OffsetX { get; set; } = 0.0;
public double OffsetY { get; set; } = 0.0;
public double Width { get; set; } = 0.0;
public double Height { get; set; } = 0.0;
public Crop Clone() => new()
{
ScaleX = ScaleX,
ScaleY = ScaleY,
OffsetX = OffsetX,
OffsetY = OffsetY,
Width = Width,
Height = Height,
};
}
Code that throws exception at context.SaveChangesAsync()
(shortened a bit for readability, find full version here: https://github.com/MilchbarBaden/Buttons/blob/bug-sqlite-update/Buttons/Controllers/ButtonController.cs#L178)
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Crop(int id, double x, double y, double width, double height, double scaleX, double scaleY)
{
var button = context.Buttons.SingleOrDefault(b => b.Id == id);
if (button == null)
{
return RedirectToAction(nameof(Index));
}
if (button.Status == ButtonStatus.Printed)
{
return RedirectToAction(nameof(Index));
}
button.Crop = new Crop()
{
OffsetX = x,
OffsetY = y,
Width = width,
Height = height,
ScaleX = scaleX,
ScaleY = scaleY,
};
button.Status = ButtonStatus.Uploaded;
await context.SaveChangesAsync();
return RedirectToAction(nameof(Confirm), null, new { id });
}
Include stack traces
I included the output from "Sensitive data logging" too.
warn: Microsoft.EntityFrameworkCore.Model.Validation[10400]
Sensitive data logging is enabled. Log entries and exception messages may include sensitive application data; this mode should only be enabled during development.
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (28ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
PRAGMA journal_mode = 'wal';
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Owners" (
"Id" TEXT NOT NULL CONSTRAINT "PK_Owners" PRIMARY KEY,
"Name" TEXT NOT NULL
);
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE "Buttons" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_Buttons" PRIMARY KEY,
"Name" TEXT NOT NULL,
"Path" TEXT NOT NULL,
"Status" INTEGER NOT NULL,
"Crop_ScaleX" REAL NOT NULL,
"Crop_ScaleY" REAL NOT NULL,
"Crop_OffsetX" REAL NOT NULL,
"Crop_OffsetY" REAL NOT NULL,
"Crop_Width" REAL NOT NULL,
"Crop_Height" REAL NOT NULL,
"OwnerId" TEXT NOT NULL,
"Created" TEXT NOT NULL,
"LastModified" TEXT NOT NULL,
CONSTRAINT "FK_Buttons_Owners_OwnerId" FOREIGN KEY ("OwnerId") REFERENCES "Owners" ("Id") ON DELETE CASCADE
);
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE INDEX "IX_Buttons_OwnerId" ON "Buttons" ("OwnerId");
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE UNIQUE INDEX "IX_Buttons_Path" ON "Buttons" ("Path");
info: Microsoft.Hosting.Lifetime[14]
Now listening on: https://localhost:7227
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:5227
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path: C:\Projects\08_Activism\Buttons\Buttons\
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (5ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (2ms) [Parameters=[@p0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Nullable = false) (Size = 36), @p1='' (Nullable = false)], CommandType='Text', CommandTimeout='30']
INSERT INTO "Owners" ("Id", "Name")
VALUES (@p0, @p1);
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (1ms) [Parameters=[@p1='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Nullable = false) (Size = 36), @p0='JP' (Nullable = false) (Size = 2)], CommandType='Text', CommandTimeout='30']
UPDATE "Owners" SET "Name" = @p0
WHERE "Id" = @p1;
SELECT changes();
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (2ms) [Parameters=[@p0='2022-11-02T11:06:06.7879322+01:00' (DbType = DateTime), @p1='2022-11-02T11:06:06.7879902+01:00' (DbType = DateTime), @p2='HalloweenMilchbar.jpeg' (Nullable = false) (Size = 22), @p3='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Nullable = false) (Size = 36), @p4='e90b6b92c2b04ff7b1ed9fe9d2692a19.jpeg' (Nullable = false) (Size = 37), @p5='0', @p6='0', @p7='0', @p8='0', @p9='1', @p10='1', @p11='0'], CommandType='Text', CommandTimeout='30']
INSERT INTO "Buttons" ("Created", "LastModified", "Name", "OwnerId", "Path", "Status", "Crop_Height", "Crop_OffsetX", "Crop_OffsetY", "Crop_ScaleX", "Crop_ScaleY", "Crop_Width")
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11);
SELECT "Id"
FROM "Buttons"
WHERE changes() = 1 AND "rowid" = last_insert_rowid();
info: Buttons.Controllers.ButtonController[0]
Created button 1 with filename 'C:\Projects\08_Activism\Buttons\Buttons\wwwroot\buttons\e90b6b92c2b04ff7b1ed9fe9d2692a19.jpeg' for owner cb2ab41c-e262-4d3f-b860-cc221bc6e7a0
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__id_0='1'], CommandType='Text', CommandTimeout='30']
SELECT "b"."Id", "b"."Created", "b"."LastModified", "b"."Name", "b"."OwnerId", "b"."Path", "b"."Status", "b"."Crop_Height", "b"."Crop_OffsetX", "b"."Crop_OffsetY", "b"."Crop_ScaleX", "b"."Crop_ScaleY", "b"."Crop_Width"
FROM "Buttons" AS "b"
WHERE "b"."Id" = @__id_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Infrastructure[10403]
Entity Framework Core 6.0.10 initialized 'ButtonContext' using provider 'Microsoft.EntityFrameworkCore.Sqlite:6.0.10' with options: SensitiveDataLoggingEnabled
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__userId_0='cb2ab41c-e262-4d3f-b860-cc221bc6e7a0' (Size = 36)], CommandType='Text', CommandTimeout='30']
SELECT "o"."Id", "o"."Name"
FROM "Owners" AS "o"
WHERE "o"."Id" = @__userId_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@__id_0='1'], CommandType='Text', CommandTimeout='30']
SELECT "b"."Id", "b"."Created", "b"."LastModified", "b"."Name", "b"."OwnerId", "b"."Path", "b"."Status", "b"."Crop_Height", "b"."Crop_OffsetX", "b"."Crop_OffsetY", "b"."Crop_ScaleX", "b"."Crop_ScaleY", "b"."Crop_Width"
FROM "Buttons" AS "b"
WHERE "b"."Id" = @__id_0
LIMIT 2
info: Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (0ms) [Parameters=[@p5='1', @p0='2022-11-02T11:06:08.0529177+01:00' (DbType = DateTime), @p1='1009.8000000000001', @p2='57.10000000000001', @p3='56.10000000000003', @p4='1009.8000000000001'], CommandType='Text', CommandTimeout='30']
UPDATE "Buttons" SET "LastModified" = @p0, "Crop_Height" = @p1, "Crop_OffsetX" = @p2, "Crop_OffsetY" = @p3, "Crop_Width" = @p4
WHERE "Id" = @p5;
SELECT changes();
fail: Microsoft.EntityFrameworkCore.Update[10000]
An exception occurred in the database while saving changes for context type 'Buttons.Data.ButtonContext'.
System.InvalidOperationException: Cannot save changes for an entity of type 'Button' with primary key values {Id: 1} in state 'Unchanged'. This may indicate a bug in Entity Framework, please open an issue at https://go.microsoft.com/fwlink/?linkid=2142044.
at Microsoft.EntityFrameworkCore.Update.ModificationCommand.AddEntry(IUpdateEntry entry, Boolean mainEntry)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.AddUnchangedSharingEntries(IEnumerable`1 sharedTablesCommands, IList`1 entries)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.CreateModificationCommands(IList`1 entries, IUpdateAdapter updateAdapter, Func`1 generateParameterName)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.BatchCommands(IList`1 entries, IUpdateAdapter updateAdapter)+MoveNext()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
System.InvalidOperationException: Cannot save changes for an entity of type 'Button' with primary key values {Id: 1} in state 'Unchanged'. This may indicate a bug in Entity Framework, please open an issue at https://go.microsoft.com/fwlink/?linkid=2142044.
at Microsoft.EntityFrameworkCore.Update.ModificationCommand.AddEntry(IUpdateEntry entry, Boolean mainEntry)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.AddUnchangedSharingEntries(IEnumerable`1 sharedTablesCommands, IList`1 entries)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.CreateModificationCommands(IList`1 entries, IUpdateAdapter updateAdapter, Func`1 generateParameterName)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.BatchCommands(IList`1 entries, IUpdateAdapter updateAdapter)+MoveNext()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
fail: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
System.InvalidOperationException: Cannot save changes for an entity of type 'Button' with primary key values {Id: 1} in state 'Unchanged'. This may indicate a bug in Entity Framework, please open an issue at https://go.microsoft.com/fwlink/?linkid=2142044.
at Microsoft.EntityFrameworkCore.Update.ModificationCommand.AddEntry(IUpdateEntry entry, Boolean mainEntry)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.AddUnchangedSharingEntries(IEnumerable`1 sharedTablesCommands, IList`1 entries)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.CreateModificationCommands(IList`1 entries, IUpdateAdapter updateAdapter, Func`1 generateParameterName)
at Microsoft.EntityFrameworkCore.Update.Internal.CommandBatchPreparer.BatchCommands(IList`1 entries, IUpdateAdapter updateAdapter)+MoveNext()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(IEnumerable`1 commandBatches, IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(StateManager stateManager, Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Buttons.Controllers.ButtonController.Crop(Int32 id, Double x, Double y, Double width, Double height, Double scaleX, Double scaleY) in C:\Projects\08_Activism\Buttons\Buttons\Controllers\ButtonController.cs:line 204
at lambda_method233(Closure , Object )
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask`1 actionResultValueTask)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.InvokeInnerFilterAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Session.SessionMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Include provider and version information
EF Core version: 6.0.10 Database provider: Microsoft.EntityFrameworkCore.Sqlite Target framework: .NET 6.0 Operating system: Windows 10 Education 21H2 IDE: Microsoft Visual Studio Community 2022 (64-bit) - Current Version 17.3.5
@TheJP The culprit is likely calling SaveChanges from inside the change tracking event.
Note for triage: we might want to consider explicitly blocking this kind of reentrancy.
@ajcvickers Removing the SaveChanges from the ChangeTracker worked to get rid of the exception. Thanks for your help.
If I recall correctly I had to add it to correctly track LastModified. But I'm sure I'll find a way to make it work without a reentrant call.
I am facing below issue but when I take App Pool Recycle it does not come. Please guide me on this.
Cannot save changes for an entity of type 'ApiTrack' in state 'Unchanged'. This may indicate a bug in Entity Framework, please open an issue at https://go.microsoft.com/fwlink/?linkid=2142044. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the key values of the entity.