11

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

3 Answers 3

21

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.

14
  • I added the override code to my context and now the migration class does have code in it to generate a table but when running the update command it is still not building my table. I have updated the original post with the commands I am running to do this. Commented Jan 7, 2016 at 16:13
  • Does the ef database update return any output? Are you sure you’re looking at the correct database? Check your connection string to make sure what you’re working with.
    – poke
    Commented Jan 7, 2016 at 16:24
  • I am sure it is the right DB. I can delete the EFMigrationHistory table and it gets recreated, plus it is the only DB on the server. When I run the dnx ef database update command all it does is sit there then says done. Do I have to do something special since the DB was already existing just not having any tables? Commented Jan 7, 2016 at 16:26
  • You did create a new migration and that migration has a CreateTable call in the Up part, right?
    – poke
    Commented Jan 7, 2016 at 16:36
  • A new migration class was generated for me and it does contain the CreateTable command. I will post the new one in OP in just a moment Commented Jan 7, 2016 at 16:38
4

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.

0

I had the same problem and this is how I resolved it

  1. I deleted my database in SQL
  2. I changed the name I used for the previous migration. I changed from "Add-Migration InitialCreate" to "Add-Migration NewName"
1
  • This is not really helpful but this is helpful for those who are working on local databases and testing. Useful answer but not completely.
    – Kurkula
    Commented May 9, 2022 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.