21

Hey I just started using EF core and everything works fine. I call the the context.Database.Migrate() method and it creates a database. But even though my context object has a DBSet<T>, it doesn't create any tables except for the migration history.

Can anyone help me with this issue?

4
  • Have you called Add-Migration? Commented May 20, 2018 at 16:20
  • Yes I did. But I still want by db to be initiated by code itself.. Commented May 20, 2018 at 16:25
  • Add-Migration generates code, context.Database.Migrate() migrates it using that code. Commented May 20, 2018 at 16:25
  • 1
    Okay. But it still wont work. In both cases, it just creates database. not tables Commented May 20, 2018 at 16:27

5 Answers 5

31

context.Database.Migrate() in itself does not generate migrations. Instead, it processes your created migrations.

For each database change, you should call Add-Migration {sensibleName}.

Your startup class would continue to call context.Database.Migrate() which will check your database and process any outstanding migrations.

For example once you have created your database, a general rule is to call Add-Migration Initial. Calling context.Database.Migrate() once will check your database exists, create it if not, check if Initial migration is applied, and apply it if not.

If you then call Add-Migration SmallChange, the same will happen on next startup, similar to the following:

  1. Does database exist? Yes
  2. Has migration Initial been applied? Yes
  3. Has migration SmallChange been applied? No
  4. Apply Migration SmallChange

Your first migration should look a little something like this:

public partial class Initial : Migration
{
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.CreateTable(
            name: "HelloWorld",
            columns: table => new
            {
                Id = table.Column<int>(nullable: false)
                    .Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn),
                MyString = table.Column<string>(nullable: true),
            });
    }
}

If your migration doesn't look like that, it may be that your DbContext isn't correctly configured. If your tables still aren't being applied, try running the database update from your Package Manager Console and see what exactly is happening with Update-Database -Verbose

Sign up to request clarification or add additional context in comments.

8 Comments

Understood. But that's my point. I created initial migration. But my Up() and Down() methods are empty and no table is generated.
Alright - In SQL Server Management Studio (or whichever tool you're using), drop your database thats been created. Clear out your Migrations folder, and then try Add-Migration Initial again.
So now it worked. What if I add DBSet<T> later in stage. will I have to do the above steps(the command line call to Update-Database) again. Is there a way to do that in C#?
No, the context.Database.Migrate() method in your code is synonymous to Update-Database 🙂 Now that you have an initial migration in place, any changes to your DbContext (or models within) will create a differencing migration. I'd suggest you give it a try now, change a model and call Add-Migration to see what happens. TLDR Add-Migration is always required, your c.Db.Migrate() call will apply them!
Is there something like automatic migrations in EF core?
|
14

So I fought with this for a long time and I couldn't figure it out. My migrations are in the application project while my DbContext was in another.

When creating the options for the context you want to apply the migrations to you need to specify the MigrationAssembly.

serviceCollection.AddDbContext<YourContext>(options => options.UseSqlServer(_configuration.GetConnectionString("ConnectionString"), b => b.MigrationsAssembly("Your.Assembly")));

Comments

5

I did the follow and works:

  1. Erase Migrations Folder in my APP project.
  2. Standing on DataAccess project, where I got persistency declared (EF, Dbcontext, etc) 2.1 Add-Migration Initial . 2.2 Update DataBase from console.

Comments

4

I will supplement the answer that is marked as correct. In my case, the migration did not work, although everything was as in the answer above. The EF tools update helped me: dotnet tool update --global dotnet-ef

2 Comments

FYI that supplements to existing answers should be added as comments rather than as new answers.
I know, but I don't have enough reputation
2

If you don't have a database, nor any migrations created (no Migrations folder in your project), then calling Migrate will create the database without any tables.

If you want the tables to be created as well, one option is to call EnsureCreated instead of Migrate:

context.Database.EnsureCreated()

This will create the database and the tables. However, the generated database won't be updatable later using migrations. So this should only be used in limited cases, such as when testing or prototyping.

2 Comments

EnsureCreated will create the tables in your current model, but it won't create a fake migration history. This is poor advice as it will leave your database in a state where future migrations will break.
When to Use EnsureCreated() vs. Migrate() Development or Prototyping: Use EnsureCreated() for rapid development, where you may not need to manage migrations. Production Applications: In a production scenario, it's better to use migrations to track schema changes over time. This way, you have better control over the database versioning and can apply changes more deliberately.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.