Entity Framework Core: Npgsql.PostgresException: 23505: duplicate key value violates unique constraint Entity Framework Core: Npgsql.PostgresException: 23505: duplicate key value violates unique constraint postgresql postgresql

Entity Framework Core: Npgsql.PostgresException: 23505: duplicate key value violates unique constraint


If your role instance already exists, you need to Attach it to let EF know that it already exists in the database. Otherwise EF assumes it's a new instance and attempts to recreate it, causing a unique constraint violation. This is simply how EF works, you can read https://msdn.microsoft.com/en-us/data/jj592676.aspx for more details (it's about EF6 but applies to EFCore as well).

Note that you can also load your existing role from the database as you've done in your own answer (_context.Role.FirstOrDefault(...)), but this may involve an unnecessary database query. As long as you're able to fully construct your Role object in .NET, all you need to do is to attach it to your context and EF will understand that it's supposed to already exist in the database.


Is definitely something related to entity framework. Although I am creating a new user attached to an existing role, is trying to also recreate the role. I went to my and point and added the following lines before saving the entity to make sure that the role attached to the user, uses the same database context as the user being saved:

 var rl = _context.Role.FirstOrDefault(r=> r.Id==user.role.Id); user.role= rl;

Now it works...

Do I need to do this always when I have to save objects that references other objects?