Using EF6 database first with connection string from configuration in .Net 6
Create a partial class that takes a connection string as constructor argument and formats it, as shown below, before calling the base class constructor.
AdventureWorksContext.cs
public partial class AdventureWorksContext
{
public AdventureWorksContext(string connectionString)
: base($@"metadata=res://*/AdventureWorksModel.csdl|res://*/AdventureWorksModel.ssdl|res://*/AdventureWorksModel.msl;provider=System.Data.SqlClient;provider connection string='{connectionString}'")
{ }
}
Program.cs
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddScoped(_ => // Needs a partial AdventureWorksContext with a constructor that takes a connection string.
new AdventureWorksContext(builder.Configuration.GetConnectionString("AdventureWorksContext")));