ASP.NET注册页面新增字段关联Customers表及数据存储疑问
Hey there! Let's break down your questions one by one to get this sorted out.
That error pops up because your application's data model (the user class with new fields) no longer matches the actual structure of your Customers table in the database. Here's how to sync them properly:
Option 1: Use Code First Migrations (Recommended)
This is the standard, maintainable way to update your database when your model changes in ASP.NET Identity:
- Open the Package Manager Console (go to Tools > NuGet Package Manager > Package Manager Console)
- If you haven't set up migrations yet, run this command first:
Enable-Migrations - Next, generate a migration file that records your new field additions:
(You can replaceAdd-Migration AddCustomerProfileFieldsAddCustomerProfileFieldswith any descriptive name you prefer) - Finally, apply the migration to update your
Customerstable:Update-Database
This will automatically add the firstName, lastName, and address columns to your existing Customers table, resolving the mismatch error.
Option 2: Manual Table Update (For Quick Development Testing)
If you're in a dev environment and want a quick fix (not recommended for long-term use), you can manually alter the database table:
- Open your database management tool (like SQL Server Management Studio)
- Run this SQL query to add the new columns (adjust data types to match your model's property types):
ALTER TABLE Customers ADD firstName NVARCHAR(255) NULL, lastName NVARCHAR(255) NULL, address NVARCHAR(MAX) NULL;
Note: This approach is error-prone because you'll have to manually sync model and database changes every time you modify your user class.
Double-Check Your Model Mapping
Ensure your user class (usually ApplicationUser) is correctly linked to the Customers table. You should have code like this:
[Table("Customers")] public class ApplicationUser : IdentityUser { public string firstName { get; set; } public string lastName { get; set; } public string address { get; set; } // Other custom properties... }
And your DbContext should reference this user class:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { public ApplicationDbContext() : base("YourConnectionStringName") { } // Additional DbSet definitions if needed... }
If you hadn't made any customizations to ASP.NET Identity, all user registration data would be stored in a set of auto-generated default tables. The core table is AspNetUsers—this is where email, password hashes, and basic user metadata live. The framework also creates related tables like AspNetRoles, AspNetUserRoles, and AspNetClaims to handle role management and user claims.
Since you're using a custom Customers table, you've already configured Identity to use this table instead of the default AspNetUsers—that's why your modified registration page targets this table.
内容的提问来源于stack exchange,提问作者 Anaelm20

