Adding a new object results in duplicate key violation

0

I have this class:

public class User
{
    /// <summary>
    /// Unique identifier and database table key of a User.
    /// </summary>
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int ID { get; set; }

    /// <summary> Name of the User. </summary>
    public string Username { get; set; }

    /// <summary> Password of the User. </summary>
    public string Password { get; set; }

    /// <summary> Role the User is assigned to. </summary>
    public Role Role { get; set; }
}

If I create a new User and add it to a DbSet<User>:

User newUser = new User
{
    Password = passwordHash,
    Username = username,
    Role = dbRole
};


_context.Entry(newUser).State = EntityState.Added;

_context.Users.Add(newUser);

_context.SaveChanges();

I get this error:

An exception occurred in the database while saving changes for context type 'webbackend.DBContext'.
    Microsoft.EntityFrameworkCore.DbUpdateException: An error occurred while updating the entries. See the inner exception for details.
    ---> Npgsql.PostgresException (0x80004005): 23505: duplicate key value violates unique constraint "PK_Users"

The only way how I can get rid of this if by making the property ID to get-only public int ID { get; } which results in a problem at another location of my code.

How can I make entity framework to assign a properly incremented ID to a new User?

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>().HasKey(u => u.ID);
    modelBuilder.Entity<User>().ToTable("Users");
}
.net
database
entity-framework
.net-5
asked on Stack Overflow Mar 1, 2021 by ravipi4764 • edited Mar 1, 2021 by Uwe Keim

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0