使用Identity Framework Core 2插入AspNetUsers表时出现主键异常
Hey Alex, let's work through this primary key issue you're hitting with Identity Framework Core 2.0.1. Switching from string to int as the primary key for IdentityUser is totally doable—most likely there's a misconfiguration in your setup that's causing the exception. Let's break down the common fixes step by step:
1. Verify Your Custom User & DbContext Configuration
First, make sure your user class explicitly inherits from IdentityUser<int> (not the default IdentityUser, which uses string keys):
public class ApplicationUser : IdentityUser<int> { // Add your custom properties here (if any) }
Then your DbContext needs to use the matching generic Identity types to avoid key mismatches:
public class AppDbContext : IdentityDbContext<ApplicationUser, IdentityRole<int>, int> { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // Add your other DbSets here }
This is a common oversight—if you skip specifying IdentityRole<int> and int as the generic parameters, the framework will default to string-keyed roles, which clashes with your int-keyed users.
2. Check Startup.cs Identity Service Setup
In your ConfigureServices method, ensure you're registering Identity with the correct generic types:
services.AddIdentity<ApplicationUser, IdentityRole<int>>() .AddEntityFrameworkStores<AppDbContext>() .AddDefaultTokenProviders();
Again, omitting the IdentityRole<int> parameter here will lead to mismatched key types under the hood.
3. Refresh Migrations & Database
It's possible your initial migration was generated before you fully configured the int primary key. Let's reset the migration and database to ensure schema consistency:
# Remove existing migration files Remove-Migration # Generate a fresh initial migration Add-Migration InitialCreate # Update the database with the correct schema Update-Database
This ensures the AspNetUsers table in your database has an Id column of type int (not nvarchar).
4. Validate User Creation Logic
When creating users via your API, avoid manually setting the Id property (since int keys are typically auto-incremented). Your registration method should look something like this:
[HttpPost("register")] public async Task<IActionResult> Register([FromBody] RegisterModel model) { var user = new ApplicationUser { UserName = model.Username, Email = model.Email // Do NOT set Id here—let the database generate it automatically }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) return Ok("User created successfully"); return BadRequest(result.Errors); }
Also, make sure your Postman request body doesn't include an Id field (or if it does, it's a valid integer). A valid request body should look like this:
{ "username": "alex_test", "email": "alex@example.com", "password": "StrongPass123!" }
5. Explicitly Configure Auto-Increment (If Needed)
In rare cases, your database provider might not automatically detect the auto-increment setting for the int key. Add this to your DbContext's OnModelCreating method to enforce it:
protected override void OnModelCreating(ModelBuilder builder) { base.OnModelCreating(builder); // Ensure ApplicationUser.Id is auto-generated builder.Entity<ApplicationUser>() .Property(u => u.Id) .ValueGeneratedOnAdd(); }
Walk through these steps one by one—chances are the issue is a missing generic parameter or outdated migration. Let me know if you hit any specific error messages and we can narrow it down further!
内容的提问来源于stack exchange,提问作者Alex

