IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Voir le flux RSS

Blog de Hinault Romaric (.NET Core, ASP.NET Core, Azure, DevOps)

Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext

Noter ce billet
par , 11/10/2017 à 01h57 (1716 Affichages)
Entity Framework Core 2.0 : resource l’erreur Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContextFactory’



Nom : ef-logo.png
Affichages : 7960
Taille : 5,9 Ko


Lorsque vous travaillez sur une application ASP.NET Core qui utilise Entity Framework Core et que vous voulez utiliser les fonctionnalités de migrations offertes par l’outil pour par exemple, créer ou mettre à jour une base de données, il peut arriver que vous obteniez l’erreur ci-dessus à l’exécution de la commande dotnet ef migrations…

Si vous avez migrer une application ASP.NET Core 1.x vers ASP.NET Core 2.0, vous devez simplement déplacer la ligne de code permettant de procéder au « seed » de votre base de données de la classe Startup vers Program.cs :

Par exemple, ce code dans la méthode Configure de la classe Startup permettant l’initialisation de la base de données dans une application sur ASP.NET Core 1.x:

Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
app.UseMvc(routes =>
{
    routes.MapRoute(
        name: "default",
        template: "{controller=Home}/{action=Index}/{id?}");
});
 
SeedData.Initialize(app.ApplicationServices);

Va produire le message d’erreur ci-dessus à l’exécution de l’application. Il doit donc être déplacé dans le main du Program.cs comme suit :

Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
public static void Main(string[] args)
  {
    var host = BuildWebHost(args);
 
    using (var scope = host.Services.CreateScope())
   {
       var services = scope.ServiceProvider;
 
      try
        {
            SeedData.Initialize(services);
        }
     catch (Exception ex)
       {
            var logger = services.GetRequiredService<ILogger<Program>>();
            logger.LogError(ex, "An error occurred seeding the DB.");
       }
   }
 
   host.Run();
 }

Par contre, si vous essayez d’utiliser la migration pour une solution dont le DBContext est dans un projet séparé, notamment une bibliothèque de classes. Vous devez à ce moment implémenter l’interface IDesignTimeDbContextFactory dans le projet qui utilise la bibliothèque de classes. Vous pouvez le faire comme suit :

Code c# : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 
public class RazorDemoDbContextFactory : IDesignTimeDbContextFactory<RazorDemoContext>
{
 
        public RazorDemoContext CreateDbContext(string[] args)
        {
 
            var builder = new DbContextOptionsBuilder<RazorDemoContext>();
 
            IConfigurationRoot configuration = new ConfigurationBuilder()
             .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
             .AddJsonFile("appsettings.json")
             .Build();
 
           builder.UseSqlite(configuration.GetConnectionString("SqliteConnectionString"));
           return new RazorDemoContext(builder.Options);
      }
}

Avant d’exécuter la commande de migration, vous devez copier le fichier de configuration(appsettings.json) dans le dossier de génération de l’application (bin).

Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Viadeo Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Twitter Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Google Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Facebook Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Digg Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Delicious Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog MySpace Envoyer le billet « Entity Framework Core : Unable to create an object of type xxx. Add an implementation of 'IDesignTimeDbContext » dans le blog Yahoo

Mis à jour 11/10/2017 à 23h34 par Hinault Romaric

Catégories
DotNET , C# , .NET Core , ASP.NET Core , Entity Framework

Commentaires