ASP.NET Core 3.1复制主机数据库后迁移生成重复表问题咨询
问题描述
我把服务器主机上的数据库(包含所有行及数据)复制到本地后,执行Code First迁移时,生成了与原有表同名的新表(如图片所示)。请问这是什么原因导致的?如何才能沿用原有表的列及其数据?我曾尝试使用空的Up/Down迁移文件。
本地连接字符串:
Data Source=.;Initial Catalog=gasdwa7d;Integrated Security=True
我的Startup.cs代码如下:
public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext>(options => { options.UseSqlServer( Configuration.GetConnectionString("DefaultDbConnection")); options.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); }); services.AddIdentity<ApplicationUser, IdentityRole>(options => { options.Password.RequireNonAlphanumeric = false; options.Password.RequireDigit = false; options.Password.RequireLowercase = false; options.Password.RequireUppercase = false; options.Password.RequiredLength = 6; }) .AddEntityFrameworkStores<ApplicationDbContext>() .AddDefaultUI() .AddDefaultTokenProviders(); services.AddControllersWithViews(); services.AddMvc(options => options.EnableEndpointRouting = false); services.AddRazorPages(); services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser> , ApplicationUserClaimsPrincipalFactory>(); services.AddSignalR(); services.Configure<ForwardedHeadersOptions>(options => { options.KnownProxies.Add(IPAddress.Parse("192.168.1.220")); }); services.Configure<TwilioVerifySettings>(Configuration.GetSection("Twilio")); //JWT Generate Token var appSettingsSection = Configuration.GetSection("AppSettings"); services.Configure<AppSettings>(appSettingsSection); var appSettings = appSettingsSection.Get<AppSettings>(); var key = Encoding.ASCII.GetBytes(appSettings.Secret); services.AddAuthentication(x => { x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; }) .AddJwtBearer(x => { x.RequireHttpsMetadata = false; x.SaveToken = true; x.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(key), ValidateIssuer = false, ValidateAudience = false }; }); // configure DI for application services services.AddScoped<IUserService, UserService>(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); endpoints.MapHub<ChatHub>("/ChatHub"); }); } }
问题分析与解决方案
我来帮你拆解这个问题,核心是EF Core的Code First迁移机制和现有数据库的同步问题,下面给你详细说明:
为什么会生成同名新表?
主要有两个常见原因:
- 迁移历史表不匹配:EF Core依赖
__EFMigrationsHistory表跟踪已应用的迁移。你从服务器复制的数据库有自己的迁移历史,但本地项目Migrations文件夹里的迁移文件和这些记录不对应。EF会误以为当前数据库还没应用过本地的迁移,于是尝试创建所有表——但原表已存在,部分场景下EF会自动生成带后缀的同名新表(比如AspNetUsers1)来规避冲突。 - 表/架构配置不匹配:如果实体类配置的表名、架构和数据库实际表不一致(比如实体用
[Table("Users")]但数据库里是AspNetUsers,或者默认架构设为app但数据库表在dbo下),EF会认为需要创建新表匹配模型。
怎么沿用原有表和数据?
关键是让EF Core认可现有数据库和你的实体模型完全匹配,不再重复创建表。按以下步骤操作:
步骤1:确保模型与数据库结构完全一致
先核对你的实体类(比如ApplicationUser、其他业务实体)的列名、数据类型、约束,和本地数据库里的表完全对应,没有任何差异。这一步是后续操作的基础,一定要仔细检查。
步骤2:用空迁移同步历史记录
你之前尝试过空迁移,但可能没完成完整流程:
- 打开Package Manager Console(或使用CLI命令),执行:
这个命令会生成一个Add-Migration InitialSync -IgnoreChangesUp和Down方法都为空的迁移文件,它不会修改数据库,仅用于告诉EF“当前数据库已符合模型状态”。 - 接着执行:
这一步会把这个空迁移的记录添加到Update-Database__EFMigrationsHistory表中,之后EF就会认为本地数据库已与模型同步,不会再创建新表了。
步骤3:排查其他配置问题
如果上述操作后仍有问题,检查以下两点:
- 表名/架构配置:查看实体类上的
[Table]特性,确保表名与数据库完全一致;检查ApplicationDbContext的OnModelCreating方法里是否有modelBuilder.HasDefaultSchema("xxx"),若有,需确保数据库表在对应的架构下。 - 连接字符串正确性:确认你的连接字符串确实指向了复制过来的
gasdwa7d数据库,没有连接到其他库。
内容的提问来源于stack exchange,提问作者Mena Samer
相关产品推荐
相关产品推荐

