I've got a DAL with EntityFramework 6 running in .NET Framework 4.6.1 as a project. Works fine in solutions with other .NET Framework projects. Now am I going to use same DAL project referenced to my ASP.NET Core WebApi (using .NET Framework 4.6.1) and it doesn't work. The exception says:
No connection string named 'MyEntities' could be found in the application config file.
.NET Core project does not hava a web.config file, so EF6 How can I pass settings from appsettings.json in my Core project to the referenced DAL project?
I've found some examples to get EF6 working inside .NET Core projects (like https://docs.microsoft.com/en-us/aspnet/core/data/entity-framework-6), but it doesn't help me. I guess that's becouse the dbcontext is created inside the DAL project.
appsettings.json
"ConnectionStrings": {
"MyEntities": "<my connectionString>"
},
project.json
"dependencies": {
"EntityFramework": "6.1.3",
...
},
...
"frameworks": {
"net461": {
"dependencies": {
"DAL": {
"target": "project"
}
},
"imports": "dnxcore50"
}
},
Well... I didn't get the answer I would like to have. So I did a workaround and I had to change some code in the DAL project. Hopefully it didn't break some functions for other projects...
In DAL project:
Since I was working with a EF Entity with Model first, I couldn't change the model. But it created partial classes, so I did another partial class for MyEntity with a contstructor that takes a parameter.
namespace DAL.Models
{
public partial class MyEntities
{
public MyEntities(string connString) : base(connString)
{
}
}
}
And in the DAL repo I created a constructor with parameter (for injection from my .NET core project) and a private method.
public class UserRepository : IUserRepository
{
private readonly string _dbContextString;
public UserRepository(string dbContextString)
{
_dbContextString = dbContextString;
}
private MyEntities GetMyEntities()
{
return string.IsNullOrEmpty(_dbContextString) ? new MyEntities() : new MyEntities(_dbContextString);
}
...
}
And then I did a search and replace for uses of MyEntity(), from
using (var context = new MyEntities())
{
...
to
using (var context = GetMyEntities())
{
...
In my .NET core project:
In Startup.cs I added a line in ConfigureService to inject the connectionString in my repo.
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddSingleton<IUserRepository>(new UserRepository(Configuration.GetConnectionString("MyEntities")));
...
Tada, now it works with my new .NET core project and still working with the other .NET framework projects!
You have to inject the IConfiguration in required controller and pass it to the Dal project
//dependency inject it in required controller or service class
IConfiguration Config
//this will get your connection string
Config.GetSection("ConnectionStrings").GetSection("MyEntities")