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?
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:
dotnet
calls dotnet-ef.dll
dotnet-ef
collects information about the project (e.g. target framework and runtime architecture) via MSBuild and calls ef.exe
(or dotnet ef.dll
)ef.exe
loads Microsoft.EntityFrameworkCore.Design.dll
and the project assembly (either in an AppDomain
or via Reflection) and calls OperationExecutor
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.