我有这门课:
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; }
}
如果我创建一个新用户并将其添加到 DbSet<User>
:
User newUser = new User
{
Password = passwordHash,
Username = username,
Role = dbRole
};
_context.Entry(newUser).State = EntityState.Added;
_context.Users.Add(newUser);
_context.SaveChanges();
我收到此错误:
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"
如果通过将属性 ID
设置为 get-only public int ID { get; }
这会导致我的代码的另一个位置出现问题,我可以摆脱这种情况的唯一方法。
如何让实体框架为新用户分配正确递增的 ID?
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().HasKey(u => u.ID);
modelBuilder.Entity<User>().ToTable("Users");
}