Issues after upgrading to Npgsql.EntityFrameworkCore.PostgreSQL 3.0.0. Adding entity with autogenerated id
I have two tables having one of them an auto-generated serial id:
CREATE TABLE app (
app_id serial NOT NULL,
"name" text NOT NULL,
CONSTRAINT pk_app PRIMARY KEY (app_id)
);
CREATE TABLE app_user (
app_id int4 NOT NULL,
user_id int4 NOT NULL,
access_level_id text NULL,
CONSTRAINT pk_app_user PRIMARY KEY (app_id, user_id)
);
ALTER TABLE app_user
ADD CONSTRAINT fk_app_user_app_id FOREIGN KEY (app_id) REFERENCES app(app_id) ON DELETE RESTRICT;
My model contains the following classes:
public class App
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AppId { get; set; }
[Required]
public string Name { get; set; }
}
public class AppUser
{
public int AppId { get; set; }
public App App { get; set; }
public int UserId { get; set; }
public string AccessLevelId { get; set; }
}
DBContext initialization:
modelBuilder.Entity<App>().ToTable("App");
modelBuilder.Entity<AppUser>()
.ToTable("AppUser")
.HasKey(x => new { x.AppId, x.UserId });
I have a method that inserts rows in both entities within the same transaction:
public Task<int> AddApp(string name, int user)
{
var app = new App { Name = name };
_context.Set<App>().Add(app);
var appuser = new AppUser
{
AppId = app.AppId,
UserId = user,
AccessLevelId = "admin"
};
_context.Set<AppUser>().Add(appuser);
return _context.SaveChangesAsync();
}
This same code is working fine with Npgsql.EntityFrameworkCore.PostgreSQL 2.2.4 and netcore 2.2 but it fails after upgrading to Npgsql.EntityFrameworkCore.PostgreSQL 3.0.0 and netcore 3.0

In seems that the serial id is not generated automatically after adding the "App" entity resulting in a FK violation.

Same code in 2.2.4 is working because it generates a temporary id for the new entity:

This is the stack trace:
at Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal.NpgsqlModificationCommandBatch.<ConsumeAsync>d__8.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__29.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.<ExecuteAsync>d__29.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.<ExecuteAsync>d__10.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.<ExecuteAsync>d__7`2.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__95.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.<SaveChangesAsync>d__93.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
at Microsoft.EntityFrameworkCore.DbContext.<SaveChangesAsync>d__54.MoveNext()
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
I forgot mentioning that I added in void OnModelCreating(ModelBuilder modelBuilder)
modelBuilder.UseSerialColumns();
as suggested in the release notes
Sorry I haven't responded earlier. You posted the stack trace but not the actual message itself (or inner exceptions) - a simple ToString() on the exception instance should give all the details.
This is the exception, thanks!
Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
---> Npgsql.PostgresException (0x80004005): 23503: insert or update on table "app_user" violates foreign key constraint "fk_app_user_app_id"
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlConnector.<>c__DisplayClass160_0.<<DoReadMessage>g__ReadMessageLong|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Npgsql.NpgsqlDataReader.NextResult(Boolean async, Boolean isConsuming)
at Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal.NpgsqlModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
Exception data:
Severity: ERROR
SqlState: 23503
MessageText: insert or update on table "app_user" violates foreign key constraint "fk_app_user_app_id"
Detail: Key (app_id)=(-2147482646) is not present in table "app".
SchemaName: public
TableName: app_user
ConstraintName: fk_app_user_app_id
File: ri_triggers.c
Line: 2783
Routine: ri_ReportViolation
--- End of inner exception stack trace ---
at Npgsql.EntityFrameworkCore.PostgreSQL.Update.Internal.NpgsqlModificationCommandBatch.ConsumeAsync(RelationalDataReader reader, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.ReaderModificationCommandBatch.ExecuteAsync(IRelationalConnection connection, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Update.Internal.BatchExecutor.ExecuteAsync(DbContext _, ValueTuple`2 parameters, CancellationToken cancellationToken)
at Npgsql.EntityFrameworkCore.PostgreSQL.Storage.Internal.NpgsqlExecutionStrategy.ExecuteAsync[TState,TResult](TState state, Func`4 operation, Func`4 verifySucceeded, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(IList`1 entriesToSave, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.DbContext.SaveChangesAsync(Boolean acceptAllChangesOnSuccess, CancellationToken cancellationToken)
at FV.DataServices.Controllers.TestController.Test1()
Coming back to this after a while...
This issue is happening with both serial and identity columns
Performing an intermediate SaveAsync() call before adding the second entity makes it work again.
So it seems that the identity value generation logic has been moved from DbSet
Next code works fine:
public async Task<int> AddApp(string name, int user)
{
var app = new App { Name = name };
_context.Set<App>().Add(app);
//workaround
await _context.SaveChangesAsync();
var appuser = new AppUser
{
AppId = app.AppId,
UserId = user,
AccessLevelId = "admin"
};
_context.Set<AppUser>().Add(appuser);
return await _context.SaveChangesAsync();
}
Looking at your model again, it doesn't seem like you've actually configured a relationship between App and AppUser; I can see the database constraint in SQL, but it would seem like that constraint was created manually, outside of EF Core. Can you confirm whether this is the case?
If this is so, then the error you're seeing makes sense - EF Core isn't aware the the App must be inserted before the AppUser, because you haven't told it that. It's entirely possible that in 2.2 the insertion order was by chance OK and no exception was triggered, and a change made the order change in 3.0. Assuming I've correctly understood the situation, you should read the EF Core documentation on defining relationships in your model; once that's properly done, EF Core will issue the insert statements in the right order.
Right, the relationship is not fully defined according to the docs, the navigation property is missing. Adding it to the model makes everything work fine.
However the documentation contains the next paragraph and I thought that having the foreign key property in the dependent entity was enough (as it was in 2.2) :
If the dependent entity contains a property named <primary key property name>, <navigation property name><primary key property name>, or <principal entity name><primary key property name> then it will be configured as the foreign key.
This would be the fully defined "App" model
public class App
{
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int AppId { get; set; }
[Required]
public string Name { get; set; }
public List<AppUser> AppUsers { get; set; }
}
The fact that everything was working fine without the navigation property in 2.2 misled me about this issue. I am closing it, thanks.