I am working on an ASP.NET Core application that is running under the full .NET Framework 4.6.1. I am using Entity Framework 6 since Entity Framework Core has some limitations as of now (specially with many-to-many relationships). I am trying to understand how to properly setup and use Entity Framework through ASP.NET Core's Dependency Injection.
Question 1
Should MyContext inherit System.Data.Entity.DbContext or Microsoft.Data.Entity.DbContext?
Question 2
Which of these would be the correct way of setting it up as a service, so that it can be injected in constructors?
private const string ConString = "myConnectionString";
public void ConfigureServices(IServiceCollection services)
{
//FIRST WAY - requires MyContext to be of type Microsoft.Data.Entity.DbContext
services.AddDbContext<MyContext>(options => { });
//SECOND WAY - requires MyContext to be of type Microsoft.Data.Entity.DbContext
services.AddEntityFramework.AddDbContext<MyContext>(options => { });
//THIRD WAY
services.AddTransient(provider => new MyContext(ConString));
//FOURTH WAY
services.AddScoped(provider => new MyContext(ConString));
}
Although the differences between AddTransient and AddScoped are well defined in the documentation.
Question 3
In which of the cases above is this required, assuming that I am using SQL Server?
services.AddEntityFrameworkSqlServer();