__EFMigrationsHistory 仍然为空,即使数据库已创建。

huangapple go评论148阅读模式
英文:

__EFMigrationsHistory remains empty even though the database is created

问题

I have translated the provided text:

嗨,我在EF Core 6中遇到了一个问题,即迁移的历史表仍然为空,但是当我检查SQL Server时,数据库已成功创建并且所有表也都创建了。
我使用了Code-First方法,所以我运行Add-Migration <name>来生成迁移。
当我运行Update-Database时,一切都正常运行。
我所做的是将EF Core从6.0.16升级到6.0.21,然后在我的模型中添加了一个新的实体mytablename,所以我生成了它的迁移。然后我运行Update-Database,现在它给了我这个错误:
Microsoft.Data.SqlClient.SqlException (0x80131904): 数据库中已存在一个名为'AspNetRoles'的对象。错误编号:2714,状态:6,类:16
mytablename已创建,但__EFMigrationsHistory未更新。
我尝试了一些解决方案,比如删除数据库并从头开始重新创建,然后尝试删除数据库和所有迁移并重新生成它们,但仍然没有解决问题,仍然出现相同的错误。
谢谢您帮助我,我是EF Core和DotNet产品的新手。

我尝试了一些解决方案,比如删除数据库并从头开始重新创建,然后尝试删除数据库和所有迁移并重新生成它们,但仍然没有解决问题,仍然出现相同的错误。
谢谢您帮助我,我是EF Core和DotNet产品的新手。
以下是第一个迁移:

  1. public partial class CreateIdentitySchema : Migration
  2. {
  3. protected override void Up(MigrationBuilder migrationBuilder)
  4. {
  5. migrationBuilder.CreateTable(
  6. name: &quot;AspNetRoles&quot;,
  7. columns: table =&gt; new
  8. {
  9. Id = table.Column&lt;string&gt;(nullable: false),
  10. Name = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  11. NormalizedName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  12. ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true)
  13. },
  14. constraints: table =&gt;
  15. {
  16. table.PrimaryKey(&quot;PK_AspNetRoles&quot;, x =&gt; x.Id);
  17. });
  18. // 其他表的创建也在此处
  19. }
  20. protected override void Down(MigrationBuilder migrationBuilder)
  21. {
  22. migrationBuilder.DropTable(
  23. name: &quot;AspNetRoleClaims&quot;);
  24. // 其他表的删除也在此处
  25. }
  26. }

当我手动填充__EFMigrationsHistory并运行update-database时,一切正常,但当我删除数据库并重新运行update-database时,会出现相同的错误。
当我运行dotnet ef migrations list时:

> 00000000000000_CreateIdentitySchema (待处理)
>
> 20230807142821_CreateAppDb (待处理)
>
> 20230809091829_AppTable (待处理)
>
> 20230809100343_UserPersonalData (待处理)
>
> 20230810084347_db (待处理)
>

>
> 程序:
>

  1. public static class Program
  2. {
  3. public static async Task Main(string[] args)
  4. {
  5. // 程序配置在此处
  6. }
  7. }

>
> DbContext
>

  1. public class ApplicationDbContext :
  2. IdentityDbContext&lt;ApplicationUser&gt;
  3. {
  4. // DbContext配置在此处
  5. }

请注意,代码中的&quot;应该是",我已经做了修正。

英文:

Hi I have an issue with EF Core 6 that is the history table of migrations remains empty but when I check the sql server the db is created successfully with all the tables are created also.
I use Code-first approach so I run Add-Migration &lt;name&gt; to generate migrations.
When I run Update-Database I was running perfectly fine.
what I did is updating EF Core from 6.0.16 to 6.0.21, Added new Entity mytablename to my models so I
generate its migration. then I run Update-Database it gives me now
Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named &#39;AspNetRoles&#39; in the database. Error Number:2714,State:6,Class:16
mytablename is created but __EFMigrationsHistory is not updated.
I tried some solutions like drop db and recreated from scratch, then I tried deleting db and all migrations and regenerate them but it did not work still same error.
thank you for helping me I am new to EF Core and DotNet products.

I tried some solutions like dropping db and recreated it from scratch, then I tried deleting db and all migrations and regenerate them but it did not work still same error.
thank you for helping me I am new to EF Core and DotNet products.
here is the first migration:

  1. public partial class CreateIdentitySchema : Migration
  2. {
  3. protected override void Up(MigrationBuilder migrationBuilder)
  4. {
  5. migrationBuilder.CreateTable(
  6. name: &quot;AspNetRoles&quot;,
  7. columns: table =&gt; new
  8. {
  9. Id = table.Column&lt;string&gt;(nullable: false),
  10. Name = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  11. NormalizedName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  12. ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true)
  13. },
  14. constraints: table =&gt;
  15. {
  16. table.PrimaryKey(&quot;PK_AspNetRoles&quot;, x =&gt; x.Id);
  17. });
  18. migrationBuilder.CreateTable(
  19. name: &quot;AspNetUsers&quot;,
  20. columns: table =&gt; new
  21. {
  22. Id = table.Column&lt;string&gt;(nullable: false),
  23. UserName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  24. NormalizedUserName = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  25. Email = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  26. NormalizedEmail = table.Column&lt;string&gt;(maxLength: 256, nullable: true),
  27. EmailConfirmed = table.Column&lt;bool&gt;(nullable: false),
  28. PasswordHash = table.Column&lt;string&gt;(nullable: true),
  29. SecurityStamp = table.Column&lt;string&gt;(nullable: true),
  30. ConcurrencyStamp = table.Column&lt;string&gt;(nullable: true),
  31. PhoneNumber = table.Column&lt;string&gt;(nullable: true),
  32. PhoneNumberConfirmed = table.Column&lt;bool&gt;(nullable: false),
  33. TwoFactorEnabled = table.Column&lt;bool&gt;(nullable: false),
  34. LockoutEnd = table.Column&lt;DateTimeOffset&gt;(nullable: true),
  35. LockoutEnabled = table.Column&lt;bool&gt;(nullable: false),
  36. AccessFailedCount = table.Column&lt;int&gt;(nullable: false)
  37. },
  38. constraints: table =&gt;
  39. {
  40. table.PrimaryKey(&quot;PK_AspNetUsers&quot;, x =&gt; x.Id);
  41. });
  42. migrationBuilder.CreateTable(
  43. name: &quot;AspNetRoleClaims&quot;,
  44. columns: table =&gt; new
  45. {
  46. Id = table.Column&lt;int&gt;(nullable: false)
  47. .Annotation(&quot;SqlServer:ValueGenerationStrategy&quot;, SqlServerValueGenerationStrategy.IdentityColumn),
  48. RoleId = table.Column&lt;string&gt;(nullable: false),
  49. ClaimType = table.Column&lt;string&gt;(nullable: true),
  50. ClaimValue = table.Column&lt;string&gt;(nullable: true)
  51. },
  52. constraints: table =&gt;
  53. {
  54. table.PrimaryKey(&quot;PK_AspNetRoleClaims&quot;, x =&gt; x.Id);
  55. table.ForeignKey(
  56. name: &quot;FK_AspNetRoleClaims_AspNetRoles_RoleId&quot;,
  57. column: x =&gt; x.RoleId,
  58. principalTable: &quot;AspNetRoles&quot;,
  59. principalColumn: &quot;Id&quot;,
  60. onDelete: ReferentialAction.Cascade);
  61. });
  62. migrationBuilder.CreateTable(
  63. name: &quot;AspNetUserClaims&quot;,
  64. columns: table =&gt; new
  65. {
  66. Id = table.Column&lt;int&gt;(nullable: false)
  67. .Annotation(&quot;SqlServer:ValueGenerationStrategy&quot;, SqlServerValueGenerationStrategy.IdentityColumn),
  68. UserId = table.Column&lt;string&gt;(nullable: false),
  69. ClaimType = table.Column&lt;string&gt;(nullable: true),
  70. ClaimValue = table.Column&lt;string&gt;(nullable: true)
  71. },
  72. constraints: table =&gt;
  73. {
  74. table.PrimaryKey(&quot;PK_AspNetUserClaims&quot;, x =&gt; x.Id);
  75. table.ForeignKey(
  76. name: &quot;FK_AspNetUserClaims_AspNetUsers_UserId&quot;,
  77. column: x =&gt; x.UserId,
  78. principalTable: &quot;AspNetUsers&quot;,
  79. principalColumn: &quot;Id&quot;,
  80. onDelete: ReferentialAction.Cascade);
  81. });
  82. migrationBuilder.CreateTable(
  83. name: &quot;AspNetUserLogins&quot;,
  84. columns: table =&gt; new
  85. {
  86. LoginProvider = table.Column&lt;string&gt;(maxLength: 128, nullable: false),
  87. ProviderKey = table.Column&lt;string&gt;(maxLength: 128, nullable: false),
  88. ProviderDisplayName = table.Column&lt;string&gt;(nullable: true),
  89. UserId = table.Column&lt;string&gt;(nullable: false)
  90. },
  91. constraints: table =&gt;
  92. {
  93. table.PrimaryKey(&quot;PK_AspNetUserLogins&quot;, x =&gt; new { x.LoginProvider, x.ProviderKey });
  94. table.ForeignKey(
  95. name: &quot;FK_AspNetUserLogins_AspNetUsers_UserId&quot;,
  96. column: x =&gt; x.UserId,
  97. principalTable: &quot;AspNetUsers&quot;,
  98. principalColumn: &quot;Id&quot;,
  99. onDelete: ReferentialAction.Cascade);
  100. });
  101. migrationBuilder.CreateTable(
  102. name: &quot;AspNetUserRoles&quot;,
  103. columns: table =&gt; new
  104. {
  105. UserId = table.Column&lt;string&gt;(nullable: false),
  106. RoleId = table.Column&lt;string&gt;(nullable: false)
  107. },
  108. constraints: table =&gt;
  109. {
  110. table.PrimaryKey(&quot;PK_AspNetUserRoles&quot;, x =&gt; new { x.UserId, x.RoleId });
  111. table.ForeignKey(
  112. name: &quot;FK_AspNetUserRoles_AspNetRoles_RoleId&quot;,
  113. column: x =&gt; x.RoleId,
  114. principalTable: &quot;AspNetRoles&quot;,
  115. principalColumn: &quot;Id&quot;,
  116. onDelete: ReferentialAction.Cascade);
  117. table.ForeignKey(
  118. name: &quot;FK_AspNetUserRoles_AspNetUsers_UserId&quot;,
  119. column: x =&gt; x.UserId,
  120. principalTable: &quot;AspNetUsers&quot;,
  121. principalColumn: &quot;Id&quot;,
  122. onDelete: ReferentialAction.Cascade);
  123. });
  124. migrationBuilder.CreateTable(
  125. name: &quot;AspNetUserTokens&quot;,
  126. columns: table =&gt; new
  127. {
  128. UserId = table.Column&lt;string&gt;(nullable: false),
  129. LoginProvider = table.Column&lt;string&gt;(maxLength: 128, nullable: false),
  130. Name = table.Column&lt;string&gt;(maxLength: 128, nullable: false),
  131. Value = table.Column&lt;string&gt;(nullable: true)
  132. },
  133. constraints: table =&gt;
  134. {
  135. table.PrimaryKey(&quot;PK_AspNetUserTokens&quot;, x =&gt; new { x.UserId, x.LoginProvider, x.Name });
  136. table.ForeignKey(
  137. name: &quot;FK_AspNetUserTokens_AspNetUsers_UserId&quot;,
  138. column: x =&gt; x.UserId,
  139. principalTable: &quot;AspNetUsers&quot;,
  140. principalColumn: &quot;Id&quot;,
  141. onDelete: ReferentialAction.Cascade);
  142. });
  143. migrationBuilder.CreateIndex(
  144. name: &quot;IX_AspNetRoleClaims_RoleId&quot;,
  145. table: &quot;AspNetRoleClaims&quot;,
  146. column: &quot;RoleId&quot;);
  147. migrationBuilder.CreateIndex(
  148. name: &quot;RoleNameIndex&quot;,
  149. table: &quot;AspNetRoles&quot;,
  150. column: &quot;NormalizedName&quot;,
  151. unique: true,
  152. filter: &quot;[NormalizedName] IS NOT NULL&quot;);
  153. migrationBuilder.CreateIndex(
  154. name: &quot;IX_AspNetUserClaims_UserId&quot;,
  155. table: &quot;AspNetUserClaims&quot;,
  156. column: &quot;UserId&quot;);
  157. migrationBuilder.CreateIndex(
  158. name: &quot;IX_AspNetUserLogins_UserId&quot;,
  159. table: &quot;AspNetUserLogins&quot;,
  160. column: &quot;UserId&quot;);
  161. migrationBuilder.CreateIndex(
  162. name: &quot;IX_AspNetUserRoles_RoleId&quot;,
  163. table: &quot;AspNetUserRoles&quot;,
  164. column: &quot;RoleId&quot;);
  165. migrationBuilder.CreateIndex(
  166. name: &quot;EmailIndex&quot;,
  167. table: &quot;AspNetUsers&quot;,
  168. column: &quot;NormalizedEmail&quot;);
  169. migrationBuilder.CreateIndex(
  170. name: &quot;UserNameIndex&quot;,
  171. table: &quot;AspNetUsers&quot;,
  172. column: &quot;NormalizedUserName&quot;,
  173. unique: true,
  174. filter: &quot;[NormalizedUserName] IS NOT NULL&quot;);
  175. }
  176. protected override void Down(MigrationBuilder migrationBuilder)
  177. {
  178. migrationBuilder.DropTable(
  179. name: &quot;AspNetRoleClaims&quot;);
  180. migrationBuilder.DropTable(
  181. name: &quot;AspNetUserClaims&quot;);
  182. migrationBuilder.DropTable(
  183. name: &quot;AspNetUserLogins&quot;);
  184. migrationBuilder.DropTable(
  185. name: &quot;AspNetUserRoles&quot;);
  186. migrationBuilder.DropTable(
  187. name: &quot;AspNetUserTokens&quot;);
  188. migrationBuilder.DropTable(
  189. name: &quot;AspNetRoles&quot;);
  190. migrationBuilder.DropTable(
  191. name: &quot;AspNetUsers&quot;);
  192. }
  193. }

When I populate __EFMigrationsHistory manually and run update-database it works fine , but when I drop the db and rerun update-database it gives the same error.
When I run dotnet ef migrations list:

> 00000000000000_CreateIdentitySchema (Pending)
>
> 20230807142821_CreateAppDb (Pending)
>
> 20230809091829_AppTable (Pending)
>
> 20230809100343_UserPersonalData (Pending)
>
> 20230810084347_db (Pending)
>

>
> Program:
>

  1. public static class Program
  2. {
  3. public static async Task Main(string[] args)
  4. {
  5. var builder = WebApplication.CreateBuilder(args);
  6. // Add services to the container.
  7. var connectionString = builder.Configuration.GetConnectionString(&quot;DefaultConnection&quot;) ?? throw new InvalidOperationException(&quot;Connection string &#39;DefaultConnection&#39; not found.&quot;);
  8. builder.Services.AddDbContext&lt;ApplicationDbContext&gt;(options =&gt;
  9. options.UseSqlServer(connectionString));
  10. builder.Services.AddDatabaseDeveloperPageExceptionFilter();
  11. builder.Services.AddDefaultIdentity&lt;ApplicationUser&gt;(options =&gt; options.SignIn.RequireConfirmedAccount = true)
  12. .AddRoles&lt;IdentityRole&gt;()
  13. .AddEntityFrameworkStores&lt;ApplicationDbContext&gt;();
  14. builder.Services.AddControllersWithViews();
  15. //authorization to apps policies
  16. builder.Services.AddAuthorization(options =&gt;
  17. {
  18. options.AddPolicy(&quot;DelibAppAccess&quot;, policy =&gt;
  19. policy.RequireClaim(&quot;AllowedToAppName&quot;));
  20. });
  21. builder.Services.AddScoped&lt;IApplicationService, ApplicationService&gt;();
  22. builder.Services.AddScoped&lt;IRoleService, RoleService&gt;();
  23. builder.Services.AddScoped&lt;IRegisterService, RegisterService&gt;();
  24. //identity password
  25. builder.Services.Configure&lt;IdentityOptions&gt;(options =&gt;
  26. {
  27. // Default Password settings.
  28. options.Password.RequireDigit = false;
  29. options.Password.RequireLowercase = false;
  30. options.Password.RequireNonAlphanumeric = false;
  31. options.Password.RequireUppercase = false;
  32. options.Password.RequiredLength = 6;
  33. options.Password.RequiredUniqueChars = 0;
  34. });
  35. var app = builder.Build();
  36. // Configure the HTTP request pipeline.
  37. if (app.Environment.IsDevelopment())
  38. {
  39. app.UseMigrationsEndPoint();
  40. }
  41. else
  42. {
  43. app.UseExceptionHandler(&quot;/Home/Error&quot;);
  44. // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
  45. app.UseHsts();
  46. }
  47. app.UseHttpsRedirection();
  48. app.UseStaticFiles();
  49. app.UseRouting();
  50. app.UseAuthentication();
  51. app.UseAuthorization();
  52. app.MapControllerRoute(
  53. name: &quot;default&quot;,
  54. pattern: &quot;{controller=Home}/{action=Index}/{id?}&quot;);
  55. app.MapRazorPages();
  56. using (var scope = app.Services.CreateScope())
  57. {
  58. var roleManager = scope.ServiceProvider.GetRequiredService&lt;RoleManager&lt;IdentityRole&gt;&gt;();
  59. var roles = new[] { &quot;SuperAdmin&quot;, &quot;Admin&quot;, &quot;Member&quot;, &quot;Guest&quot; };
  60. foreach (var role in roles)
  61. {
  62. if (!await roleManager.RoleExistsAsync(role))
  63. await roleManager.CreateAsync(new IdentityRole(role));
  64. }
  65. var dbContext = scope.ServiceProvider.GetService&lt;ApplicationDbContext&gt;();
  66. var apps = new[] { &quot;AppName&quot; };
  67. if (dbContext is not null)
  68. {
  69. foreach (var application in apps)
  70. {
  71. if (!dbContext.Applications!.Where(a =&gt; a.Label.Equals(application)).Any())
  72. {
  73. dbContext.Applications!.Add(new Application() { Label = application });
  74. }
  75. }
  76. await dbContext.SaveChangesAsync();
  77. }
  78. }
  79. app.Run();
  80. }
  81. }

>
> DbContext
>

  1. public class ApplicationDbContext :
  2. IdentityDbContext&lt;ApplicationUser&gt;
  3. {
  4. public ApplicationDbContext()
  5. {
  6. }
  7. public ApplicationDbContext(DbContextOptions&lt;ApplicationDbContext&gt; options) : base(options)
  8. {
  9. try
  10. {
  11. if (Database.GetService&lt;IDatabaseCreator&gt;() is RelationalDatabaseCreator databaseCreator)
  12. {
  13. if (!databaseCreator.CanConnect())
  14. {
  15. databaseCreator.CreateAsync().Wait();
  16. }
  17. if (!databaseCreator.HasTables())
  18. {
  19. databaseCreator.CreateTablesAsync().Wait();
  20. }
  21. }
  22. }
  23. catch (Exception ex)
  24. {
  25. Console.WriteLine(ex.ToString());
  26. }
  27. }
  28. protected override void OnModelCreating(ModelBuilder modelBuilder)
  29. {
  30. //filtering users by isEnabled
  31. modelBuilder.Entity&lt;ApplicationUser&gt;().HasQueryFilter(user =&gt; user.IsEnabled);
  32. base.OnModelCreating(modelBuilder);
  33. }
  34. public DbSet&lt;Application&gt;? Applications { get; set; }
  35. }

答案1

得分: 0

我通过移除以下代码解决了这个问题:

  1. try
  2. {
  3. if (Database.GetService<IDatabaseCreator>() is RelationalDatabaseCreator databaseCreator)
  4. {
  5. if (!databaseCreator.CanConnect())
  6. {
  7. databaseCreator.CreateAsync().Wait();
  8. }
  9. if (!databaseCreator.HasTables())
  10. {
  11. databaseCreator.CreateTablesAsync().Wait();
  12. }
  13. }
  14. }
  15. catch (Exception ex)
  16. {
  17. Console.WriteLine(ex.ToString());
  18. }
英文:

I solved the problem by removing:

  1. try
  2. {
  3. if (Database.GetService&lt;IDatabaseCreator&gt;() is RelationalDatabaseCreator databaseCreator)
  4. {
  5. if (!databaseCreator.CanConnect())
  6. {
  7. databaseCreator.CreateAsync().Wait();
  8. }
  9. if (!databaseCreator.HasTables())
  10. {
  11. databaseCreator.CreateTablesAsync().Wait();
  12. }
  13. }
  14. }
  15. catch (Exception ex)
  16. {
  17. Console.WriteLine(ex.ToString());
  18. }

huangapple
  • 本文由 发表于 2023年8月10日 21:01:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875974.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定