Arkadi
Arkadi

Reputation: 1357

EF Core 2 Migrate method doesn't create tables in DB

I have .netcore 2.0 app with N-Tier Architecture, I have implemented ApplicationDbContext in Data Access Layer... Now I'm trying to Add new Entities, for example I have created entity Test2:

namespace MyProject.Domain
{
    public class Test2
    {
        public int Id { get; set; }

        public string FirstName { get; set; }
    }
}

Then I added DbSet in ApplicationDbContext:

namespace MyProject.Infrastructure.Implementation.MySql.Contexts
{
    public class ApplicationDbContext : DbContext, IApplicationDbContext
    {
        private readonly IConfiguration _configuration;

        public ApplicationDbContext(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseMySql(
                _configuration.GetConnectionString("MySql"));
        }

        public DbSet<Test> Test { get; set; }

        public DbSet<Test2> Test2 { get; set; }
    }
}

Then I have called .Migrate() method in BaseEnfine.cs:

namespace MyProject.Infrastructure.Implementation.MySql
{
    public class BaseEngine : IBaseEngine
    {
        private readonly ApplicationDbContext _context;

        protected ApplicationDbContext Db => _context;

        protected BaseEngine(ApplicationDbContext context)
        {
            _context = context;

            if (!_context.Database.EnsureCreated())
            {
                _context.Database.Migrate();
                _context.Database.EnsureCreated();
            }
        }
    }
}

But when I refresh DB there's no table Test2.. Any ideas?

Upvotes: 0

Views: 2105

Answers (2)

Alamgir
Alamgir

Reputation: 686

I face the same problem and solved as follow. I was using entityframeworkcore. at first run this command from Package Manager Console

Update-Database -Migration 0

Then remove all migrations using this command

Remove-Migration

Then Create migration as like

Add-Migration initial_migration

Finally run update Command

Update-Database

Upvotes: 1

Andrey Alonzov
Andrey Alonzov

Reputation: 357

You should first add migrations before migrating your DB. There are 2 ways:

  1. Using Package manager console:

    Add-Migration InitialMigration

  2. With dotnet CLI:

    Add following code to your .csproj file:

    <ItemGroup> <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.1" /> </ItemGroup>

    cd to your project directory with command line and run

    run dotnet ef migrations add InitialMigration

In most cases it is better to not apply migrations in your app. You can use CLI to migrate database or generate scripts for migrations.

dotnet ef database update
dotnet ef migrations script

Read more about dotnet ef on MSDN

Make sure dotnet is added to the PATH.

Upvotes: 2

Related Questions