Create a dotnet tool for EF Core data seed

asp.net-core dotnet-cli entity-framework-core

Question

As mentioned in this post I am seeding database data on the Startup of an ASP.NET Core project as follows:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) {

  using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope()) {  
    var context = serviceScope.ServiceProvider.GetService<MyContext>();       
    context.Database.Migrate();
    context.EnsureSeedData();

  }

}

But the same post also recommends to seed data manually,

Please note that, in general, it is recommended to apply these operations manually (rather than performing migrations and seeding automatically on startup), to avoid racing conditions when there are multiple servers, and unintentional changes.

which I would prefer and using a dotnet tool as follows:

dotnet seed -c <Context> -s <SeedData>

where:
- Context is the DbContext to be used. Default is used if none is specified.
- SeedData is a class containing the Data Insertion logic.

Is it possible to create such a custom dotnet tool?

Can the DbContext be used inside the tool?

1
4
2/6/2017 1:14:45 PM

Accepted Answer

It's not trivial to create a general-purpose dotnet CLI tool that loads a project's assembly.

You can start digging around in the aspnet/EntityFramework.Tools and aspnet/EntityFramework repos. The general process flow is:

  1. dotnet calls dotnet-ef.dll
  2. dotnet-ef collects information about the project (e.g. target framework and runtime architecture) via MSBuild and calls ef.exe (or dotnet ef.dll)
  3. ef.exe loads Microsoft.EntityFrameworkCore.Design.dll and the project assembly (either in an AppDomain or via Reflection) and calls OperationExecutor
  4. Microsoft.EntityFrameworkCore.Design instantiates the DbContext and performs operations on it.

You can simplify this dramatically by making your tool less general-purpose and more specific to your project. And even further by just making a console app instead of a dotnet tool.

3
2/9/2017 6:51:51 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow