Entity Framework 7 migration not creating tables

asp.net-core c# entity-framework-core

Question

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. I have created my DbContext and created a class, then set a DbSet<> inside my context. I ran the commands to enable migrations and create the first migration, then rand the command to update the database. Everything looked to work fine, no errors came up, but when I look at the database only the EFMigraitonsHistory table was created. 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:

    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):

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. 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");
        }
    }
}

Accepted Answer

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. And then you have a project JobSight.WebUI which is the actual ASP project containing the Startup.cs with the database setup.

This is causing problems because by default EF will just assume to find everything in the current assembly. 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. 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.

So to fix this, you need to create the migrations in the DAL project. You can do that by specifying the project when you call the ef command:

dnx ef migrations add Example -p JobSight.DAL

You can verify that this worked by running dnx ef migrations list afterwards. This should now return the Example migration; 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. 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. You need to do that before you can run the list command above.

Finally, for some more information about this, see this issue.


Popular Answer

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. But dotnet ef database update only created the MigrationsHistory table and dotnet ef migrations list did not return any migrations.

It turned out that the problem was that the Migrations folder was excluded from the Visual Studio project. Once I included it again, everything worked fine.



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why