We have several older class libraries which are targeting .NET Framework 4.8 and using Entity Framework 6.
We are also planning on building a brand new application and would be interested in using .NET 5 with Blazor but are not sure whether or not we can successfully reference and utilize these libraries.
I have added references to the old projects in my Blazor App and also referenced Entity Framework 6. I added the DBContext to the ConfigureServices method like so:
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddScoped<MyDBContext>(); // reference to my EF6 DB Context
}
I also added the Connection String to appsettings.json like so:
"ConnectionStrings": {
"MyConnectionString": "XXXXXXXXXXXXXXXXXXXXX" // connection details ommitted
}
When I try to run the application and use code that references the database, I receive the following error:
No connection string named 'MyConnectionString' could be found in the application config file.
This seems strange since the Connection String is in the appsettings.json file.
So, am I just making a silly mistake somewhere, or am I trying to do something that's not possible?
EF 6.3+ supports .NET Standard 2.1 and .NET 5 targets .NET Standard 2.1.
But if you have custom assemblies targeting .NET Framework, you'll need to recompile them to target .NET Standard 2.1 before you can use them in .NET 5. This should be simple unless you have dependencies on other libraries that haven't been ported to .NET Standard/.NET Core.
But EF6 won't be able to find the connection string by itself. You need to access the configuration and pass the connection string to the DbContext, like in this example:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<MyDBContext>(_ =>
new SchoolContext(Configuration.GetConnectionString("MyConnectionString")));
}