简体   繁体   English

实体框架7迁移不创建表

[英]Entity Framework 7 migration not creating tables

I am working with my first project using Entity Framework 7 and am connecting to a SQL Server where the Database is already created but there are no tables in it yet. 我正在使用Entity Framework 7处理我的第一个项目,并且正在连接到已经创建了数据库的SQL Server,但它还没有表。 I have created my DbContext and created a class, then set a DbSet<> inside my context. 我创建了我的DbContext并创建了一个类,然后在我的上下文中设置了一个DbSet<> I ran the commands to enable migrations and create the first migration, then rand the command to update the database. 我运行命令以启用迁移并创建第一次迁移,然后使用rand命令更新数据库。 Everything looked to work fine, no errors came up, but when I look at the database only the EFMigraitonsHistory table was created. 一切看起来都很好,没有出现任何错误,但是当我查看数据库时,只创建了EFMigraitonsHistory表。 When I look at the class that was created for the initial migration it is essentially blank. 当我查看为初始迁移创建的类时,它基本上是空白的。 What am I doing wrong? 我究竟做错了什么?

Commands I am running: 我正在运行的命令:

dnvm install latest -r coreclr
dnx ef migrations add MyFirstMigration
dnx ef database update

Context: 语境:

namespace JobSight.DAL
{
    public class JobSightDBContext : DbContext
    {
        public DbSet<NavigationMenu> NavigationMenu { get; set; }
    }
}

Table Class: 表类:

namespace JobSight.DAL
{
    public class NavigationMenu
    {
        [Required, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public Int16 ID { get; set; }

        public string ControllerName { get; set; }
        public string ActionName { get; set; }
        public string ExternalURL { get; set; }
        public string Title { get; set; }
        public Int16? ParentID { get; set; }

        public virtual NavigationMenu Parent { get; set; }
    }
}

Startup.cs: Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();

        services.AddEntityFramework()
                .AddSqlServer()
                .AddDbContext<JobSightDBContext>(options =>
                {
                    options.UseSqlServer(Configuration["Data:JobSightDatabase:ConnectionString"]);
                });
    }

Class for initial migration (autogenerated by EF): 初始迁移类(由EF自动生成):

namespace JobSight.WebUI.Migrations
{
    public partial class Initial : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
        }
    }
}

Edit: After doing what Poke has suggested this is my new auto-generated migration. 编辑:在做了Poke的建议后,这是我新的自动生成的迁移。 The table is still not being created at the database level though. 但是,该表仍未在数据库级别创建。

namespace JobSight.WebUI.Migrations
{
    public partial class MyFirstMigration : Migration
    {
        protected override void Up(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.CreateTable(
                name: "NavigationMenu",
                columns: table => new
                {
                    ID = table.Column<short>(nullable: false)
                        .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                    ActionName = table.Column<string>(nullable: true),
                    ControllerName = table.Column<string>(nullable: true),
                    ExternalURL = table.Column<string>(nullable: true),
                    ParentID = table.Column<short>(nullable: true),
                    Title = table.Column<string>(nullable: true)
                },
                constraints: table =>
                {
                    table.PrimaryKey("PK_NavigationMenu", x => x.ID);
                    table.ForeignKey(
                        name: "FK_NavigationMenu_NavigationMenu_ParentID",
                        column: x => x.ParentID,
                        principalTable: "NavigationMenu",
                        principalColumn: "ID",
                        onDelete: ReferentialAction.Restrict);
                });
        }

        protected override void Down(MigrationBuilder migrationBuilder)
        {
            migrationBuilder.DropTable("NavigationMenu");
        }
    }
}

You need to set up the entity in your database context first. 您需要首先在数据库上下文中设置实体。 At the very least, you would need to do this: 至少,您需要这样做:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<NavigationMenu>();
}

The problem with your migrations was a bit hidden in your project layout. 您的项目布局中隐藏了迁移问题。 So what you have is a JobSight.DAL project that contains the entities and the database context. 所以你拥有的是一个包含实体和数据库上下文的JobSight.DAL项目。 And then you have a project JobSight.WebUI which is the actual ASP project containing the Startup.cs with the database setup. 然后你有一个项目JobSight.WebUI ,这是一个实际的ASP项目,包含带有数据库设置的Startup.cs

This is causing problems because by default EF will just assume to find everything in the current assembly. 这会导致问题,因为默认情况下,EF只会假设查找当前程序集中的所有内容。 So if you are launching the ef command from your web project, it will create the migrations in there even if the context is in another project. 因此,如果要从Web项目启动ef命令,即使上下文位于另一个项目中,它也会在那里创建迁移。 But when you're then trying to apply the migration, EF will not find it since it will only look in the context's project. 但是,当您尝试应用迁移时,EF将无法找到它,因为它只会查看上下文的项目。

So to fix this, you need to create the migrations in the DAL project. 因此,要解决此问题,您需要在DAL项目中创建迁移。 You can do that by specifying the project when you call the ef command: 您可以通过在调用ef命令时指定项目来执行此操作:

dnx ef migrations add Example -p JobSight.DAL

You can verify that this worked by running dnx ef migrations list afterwards. 您可以通过之后运行dnx ef migrations list来验证这dnx ef migrations list This should now return the Example migration; 现在应该返回Example迁移; previously, that command didn't return anything: It could not find a migration which is the reason why the update command only said Done (without applying the migration) and the database wasn't created. 以前,该命令没有返回任何内容:它无法找到迁移,这就是update命令仅表示Done (未应用迁移)且未创建数据库的原因。 So if you now get the migration there, you can then apply it using: 因此,如果您现在可以在那里进行迁移,则可以使用以下方法应用它:

dnx ef database update

Note that since the migration is now created in the DAL project, you need to add a reference to EntityFramework.MicrosoftSqlServer there, otherwise the project will not compile. 请注意,由于现在在DAL项目中创建了迁移,因此您需要在那里添加对EntityFramework.MicrosoftSqlServer的引用,否则项目将无法编译。 You need to do that before you can run the list command above. 您需要先执行此操作,然后才能运行上面的list命令。

Finally, for some more information about this, see this issue . 最后,有关此内容的更多信息,请参阅此问题

Although this is not the answer to the original question, I post my answer here because it might help someone who has a similar problem. 虽然这不是原始问题的答案,但我在这里发布我的答案,因为它可能会帮助有类似问题的人。 My problem was also that the tables were not created, but dotnet ef migrations add InitialCreate did create 3 .cs files in the Migrations folder. 我的问题还在于没有创建表,但是dotnet ef migrations add InitialCreate确实在Migrations文件夹中创建了3.cs文件。 But dotnet ef database update only created the MigrationsHistory table and dotnet ef migrations list did not return any migrations. dotnet ef database update仅创建了MigrationsHistory表,而dotnet ef migrations list未返回任何迁移。

It turned out that the problem was that the Migrations folder was excluded from the Visual Studio project. 原来,问题是Visual Studio项目中排除了Migrations文件夹。 Once I included it again, everything worked fine. 一旦我再次包含它,一切都运行良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM