To demonstrate this issue I've created a small project using the webapi template in .NET 6.
The issue when trying to add my first migration, I get the following error (running with the verbose option);
No static method 'CreateHostBuilder(string[])' was found on class 'Program'. No application service provider was found. Finding DbContext classes in the project... Found DbContext 'BloggingContext'. Microsoft.EntityFrameworkCore.Design.OperationException: Unable to create an object of type 'BloggingContext'. For the different patterns supported at design time, see https://go.microsoft.com/fwlink/?linkid=851728
As the new .NET 6 template does not have CreateHostBuilder in the startup, the EF tools are trying to create an instance of the context class, but because I'm using DI in the constructor to obtain the configuration this error arises.
My demo project;
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.11">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.11" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.1.5" />
</ItemGroup>
</Project>
Created a models class to hold the db context and entities.
using Microsoft.EntityFrameworkCore;
namespace dotnet6apiefcore;
public class BloggingContext : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public IConfiguration _configuration { get; }
public BloggingContext(IConfiguration configuration)
{
this._configuration = configuration;
}
protected override void OnConfiguring(DbContextOptionsBuilder options) {
var connectString = _configuration.GetValue<string>("ConnectionString");
options.UseSqlServer(connectString);
}
}
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; }
}
In the program.cs I register the BloggingContext.
using dotnet6apiefcore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddDbContext<BloggingContext>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
