[SOLVED] Integration Tests | .Net Core WebApi | Fails seeds data when overriding a service in a test

Context: I've coded a custom WebApplicationFactory to setup a web host configuring an in-memory database and seeding data for User table. Expected Test: Ensure global handling exception when an exception is trown in GetById() userService method. Issue : When I run it, it fails in dbContext.SaveChanges(); logging that it couldn't seed the data, I've debug it and saw that it only happens after overriding the service.
Message: 
Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while saving the entity changes. See the inner exception for details.
---- Microsoft.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.

Stack Trace: 
ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection)
RelationalDatabase.SaveChanges(IList1 entries)
StateManager.SaveChanges(IList1 entriesToSave)
StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple2 t)
SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)
StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
DbContext.SaveChanges()
Message: 
Microsoft.EntityFrameworkCore.DbUpdateException : An error occurred while saving the entity changes. See the inner exception for details.
---- Microsoft.Data.SqlClient.SqlException : Cannot insert explicit value for identity column in table 'Users' when IDENTITY_INSERT is set to OFF.

Stack Trace: 
ReaderModificationCommandBatch.Execute(IRelationalConnection connection)
BatchExecutor.Execute(IEnumerable1 commandBatches, IRelationalConnection connection)
RelationalDatabase.SaveChanges(IList1 entries)
StateManager.SaveChanges(IList1 entriesToSave)
StateManager.SaveChanges(StateManager stateManager, Boolean acceptAllChangesOnSuccess)
<>c.<SaveChanges>b__104_0(DbContext _, ValueTuple2 t)
SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func3 operation, Func3 verifySucceeded)
StateManager.SaveChanges(Boolean acceptAllChangesOnSuccess)
DbContext.SaveChanges(Boolean acceptAllChangesOnSuccess)
DbContext.SaveChanges()
No description
No description
2 Replies
jorgedotnet
jorgedotnetOP5d ago
It was solved. My mistake has been putting the stringConnection inside OnConfiguring() method in the DbContext. , I've changed that to utilize dependency injection.
Unknown User
Unknown User4d ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?