c# - 添加表代码先迁移 Entity Framework

标签 c# entity-framework asp.net-core asp.net-identity entity-framework-migrations

迁移期间未创建新表。

迁移本身似乎是创建的

public partial class _222 : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "ToDos",
                columns: table => new
                {
                    Id = table.Column<string>(nullable: false),
                    Name = table.Column<string>(nullable: true),
                    Body = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_ToDos", x => x.Id);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable(
                name: "ToDos");
        }
    }

但是当我写 Update-Database 表时没有创建。

ApplicationDbContext

public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
            Database.EnsureCreated();
        }

        public DbSet<ToDo> ToDos { get; set; }

待办事项

public class ToDo
    {
        [Key]
        public string Id { get; set; }
        public string Name { get; set; }
        public string Body { get; set; }
    }

来自包管理器控制台中的错误

Failed executing DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
CREATE TABLE [AspNetRoles] (
    [Id] nvarchar(450) NOT NULL,
    [Name] nvarchar(256) NULL,
    [NormalizedName] nvarchar(256) NULL,
    [ConcurrencyStamp] nvarchar(max) NULL,
    CONSTRAINT [PK_AspNetRoles] PRIMARY KEY ([Id])
);

There is already an object named 'AspNetRoles' in the database.

最佳答案

错误信息很清楚。它正在尝试创建一个名为 AspNetRoles 的表,该表已存在于数据库中。由于这不是您的迁移正在创建的表,我希望这是需要首先应用的先前迁移。可能此表是手动创建的,这就是为什么迁移历史显示仍需要应用迁移的原因。如果它是开发数据库,​​也许您可​​以删除该表并允许应用迁移。另一种解决方法是找到适用的迁移并注释掉 Up 方法的内容。不过,您需要检查现有表的架构是否正确,以防发生任何更改。

关于c# - 添加表代码先迁移 Entity Framework ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55865170/

相关文章:

C# XML 反序列化和数组

c# - 在 C# 中获取 Excel 单元格背景颜色的问题

c# - 将一对多公开为一对零/一

entity-framework - 将 SimpleMembership 与 EF 模型优先结合使用

c# - 在 mvc 中使用 IViewLocationExpander

c# - 在 SQL 中克隆带有主键的行?

c# - EWS 连接出现未经授权 (401) 错误

entity-framework - Entity Framework - 代码优先模型验证

asp.net-core - 我们如何在新的asp.net vnext中存储配置数据?

c# - 回滚一个非常具体的预览包,该包导致了一个肮脏的项目