ASP.NET Core Identity合并FirstName/LastName为FullName时EF Core种子数据异常
Hey there! Let's figure out why your FullName field is only saving the last part ("McTesterson") instead of the full "Test McTesterson" in SQL Server. Here are the most likely issues and fixes to try:
1. Double-Check Your ApplicationUser Model
First, make sure your FullName property is defined correctly—no accidental typos or wrong getters that might be returning only the last name. Also, ensure you're using a proper length annotation to avoid truncation:
public class ApplicationUser : IdentityUser<int> { // Correct definition with appropriate length [StringLength(255)] // Adjust based on your needs (255 is safe for most full names) public string FullName { get; set; } // Remove old FirstName/LastName properties if you no longer need them! }
If you previously had FirstName and LastName fields, confirm they're fully removed from the model—leftover properties or logic could interfere with the new FullName field.
2. Fix Database Column Length via Migration
EF Core might have created the FullName column with a short length (e.g., if it reused settings from your old LastName field). This would truncate longer strings like "Test McTesterson".
To fix this:
- Generate a new migration to update the column:
Add-Migration UpdateFullNameColumnLength - Open the generated migration file and ensure the
FullNamecolumn has a sufficient max length:migrationBuilder.AddColumn<string>( name: "FullName", table: "AspNetUsers", maxLength: 255, // Match the length from your model annotation nullable: true); - Apply the migration to update the database:
Update-Database - Finally, verify the
AspNetUserstable in SQL Server—check that theFullNamecolumn is set tonvarchar(255)(or your chosen length).
3. Verify Your Seed Data Code
It's easy to accidentally assign the wrong value to FullName in your seed logic. Double-check that you're explicitly setting the full name:
// Correct seed data setup var testUser = new ApplicationUser { UserName = "testmc", Email = "test@example.com", FullName = "Test McTesterson" // Make sure this is the full string! }; _context.Users.Add(testUser); _context.SaveChanges();
Avoid any code that might overwrite FullName with just the last name (e.g., a leftover reference to a LastName variable).
4. Check Fluent API Configuration
If you're using Fluent API to configure your model, ensure you haven't set an overly restrictive max length for FullName:
// Correct configuration in your DbContext's OnModelCreating method modelBuilder.Entity<ApplicationUser>() .Property(u => u.FullName) .HasMaxLength(255) // Match your model's annotation .IsRequired(false); // Set to true if FullName is mandatory
If you had a previous Fluent rule for LastName, make sure it's removed so it doesn't affect the new FullName field.
内容的提问来源于stack exchange,提问作者Joe

