Je commence avec EF Core 2.0, j'ai une application console qui cible .NET 4.6.1 J'ai une classe de modèle très simple, et ce contexte:
public class ContextCore : DbContext
{
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(ConfigurationManager.ConnectionStrings["efCoreCon"].ConnectionString);
}
public DbSet<ModelC> Models { get; set; }
}
c'est la chaîne de connexion:
<add name="efCoreCon" connectionString="server=PC-MSHWF\SQLEXPRESS;database=efCoreDB;integrated security=true;" />
J'ai remarqué qu'il n'y a pas de commande pour Enable-Migrations
dans le noyau ef de la documents officiels
donc je cours Add-migration firstMigration
mais j'ai eu cette erreur:
Aucun type de configuration de migration n'a été trouvé dans l'assembly 'NewConsole'. (Dans Visual Studio, vous pouvez utiliser la commande Enable-Migrations de la console du gestionnaire de packages pour ajouter une configuration de migrations).
quand j'ai essayé Enable-Migrations, j'ai eu cette erreur:
Aucun type de contexte n'a été trouvé dans l'assembly 'NewConsole'.
Accédez à la console du gestionnaire de packages et installez les outils nécessaires avec Install-Package Microsoft.EntityFrameworkCore.Tools
. Une fois terminé, essayez d'utiliser la commande EntityFrameworkCore\Add-Migration firstMigration
.
dans Powershell CLI, tapez ceci -> dotnet ef migrations add InitialMigration
Cela installera les outils de base corrects
// 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
Correction de votre problème de bogue:
Regardez ceci réponse SO : "Vous devriez juste avoir besoin de mettre à jour la section des outils de votre fichier project.json pour inclure ceci:"
"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 :) Pour exécuter automatiquement les migrations ... dans startup.cs de votre application principale.
// 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
}
Modifiez votre .csproj où vous avez EF Core 2.0 et ajoutez:
<ItemGroup>
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />
</ItemGroup>
dotnet ef migrations add <<migration's_name>>
. Par exemple: dotnet ef migrations add Init
. Si votre projet de démarrage se trouve dans un dossier différent, vous pouvez utiliser --startup-project ../<<other_project_folder>>
En démarrant .NET Core 2 à l'aide de C # 7.1, vous pouvez avoir une méthode asynchrone Main
pour votre application, vous pouvez donc appeler toute la logique d'initialisation avant d'exécuter l'hôte, juste après la fin de la construction:
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 = "[email protected]" },
password: "1234");
}
}
//now run
Host.Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}