简体   繁体   中英

Enabling Migrations in EF core?

I'm getting started with EF Core 2.0, I have a console application targetting .NET 4.6.1 I have a very simple model class, and this context:

public class ContextCore : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["efCoreCon"].ConnectionString);
    }
    public DbSet<ModelC> Models { get; set; }
}

this is the connection string:

<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" />

I noticed that there's no command for Enable-Migrations in ef core from the official docs

so I run Add-migration firstMigration but I got this error:

No migrations configuration type was found in the assembly 'NewConsole'. (In Visual Studio you can use the Enable-Migrations command from Package Manager Console to add a migrations configuration).

when I tried Enable-Migrations , I got this error:

No context type was found in the assembly 'NewConsole'.

Go to the Package Manager Console and install the needed tools with Install-Package Microsoft.EntityFrameworkCore.Tools . When it has completed try to use the command EntityFrameworkCore\\Add-Migration firstMigration .

in powershell CLI type this --> dotnet ef migrations add InitialMigration

This enables the migration. 在此处输入图片说明


This will install the correct core tools

// Package Manger
PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 2.0.1
// or this will work inside the CLI Console
dotnet add package Microsoft.EntityFrameworkCore.Tools --version 2.0.1
// **for the current/LATEST ver. leave out version option it will install latest Install-Package Microsoft.EntityFrameworkCore.Tools 

在此处输入图片说明


Fixing your bug issue:

Look at this SO answer : "You should just need to update the tools section of your project.json file to include this:"

"Microsoft.EntityFrameworkCore.Tools": {
  "version": "2.0.1",  // I corrected this from previous answer for your version
  "imports": [
    "portable-net45+win8+dnxcore50",
    "portable-net45+win8"
  ]
}

Bonus :) To run migrations automatically ... in startup.cs of your main application.

// setup the HTTP request pipeline to check and migrate.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{           
    try
    {
        using (var migrationSvcScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>()
            .CreateScope())
        {
         migrationSvcScope.ServiceProvider.GetService<EFMigrationsMyDBContext>().Database.Migrate();
            // you can also add the data here... let me know if you need I will post it
        }
    }   
    ... // Rest of the startup stuff
}

Starting .NET Core 2 using C# 7.1, you can have an asynchronous Main method to your app, so you can call all initialization logic before you run the host, right after it has finished building:

public class Program
{
  public static async Task Main(string[] args)
  {
    //first build
    var host = CreateHostBuilder(args).Build();

    //initialize
    using (var serviceScope = host.Services.CreateScope())
    {
      var serviceProvider = serviceScope.ServiceProvider;
      var isDevelopment = 
        serviceProvider.GetRequiredService<IWebHostEnvironment>().IsDevelopment();

      using var context = serviceProvider.GetRequiredService<AppDbContext>();


      if (isDevelopment)
        await context.Database.EnsureCreatedAsync();
      else
        await context.Database.MigrateAsync();

      if (isDevelopment)
      {
        using var userManager = 
          serviceProvider.GetRequiredService<UserManager<AppUser>>();
        await userManager
          .CreateAsync(new AppUser { UserName = "dummy", Email = "dummy@dumail.com" },
          password: "1234");
      }
    }

    //now run
    host.Run();
  }

  public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
      .ConfigureWebHostDefaults(webBuilder =>
      {
        webBuilder.UseStartup<Startup>();
      });
}

Edit your .csproj where you have EF Core 2.0 and add:

<ItemGroup>
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
  1. Open Windows PowerShell
  2. Go to directory where you have EF Core 2.0
  3. Type dotnet ef migrations add <<migration's_name>> . For instance: dotnet ef migrations add Init . If your startup project is in different folder then you can use --startup-project ../<<other_project_folder>>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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