Camilo Terevinto
Camilo Terevinto

Reputation: 32062

Setting up Entity Framework in ASP.NET Core

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();

Upvotes: 3

Views: 8154

Answers (3)

Simon_Weaver
Simon_Weaver

Reputation: 146180

Regarding AddEntityFrameworkSqlServer():

If you are using within ASP.NET:

You are simply not supposed to call AddEntityFrameworkSqlServer() on your ASP.NET container - that configures all of EF's services on that container; the right way to use EF in almost all cases is to let it configure its own internal service provider. In other words, just call UseSqlServer() as indicated in all the tutorials, and EF will set up an internal DI service provider (completely distinct from the ASP.NET one), and will configure its own internal IMemoryCache there.

From https://github.com/dotnet/efcore/issues/12905

Upvotes: 0

Tom
Tom

Reputation: 836

Question 1: System.Data.Entity.DbContext

Question 2:

services.AddScoped(provider => new MyContext(ConString));

you want 1 context per web request

Question 3: you don't need this

Those other extension are for using EF Core NOT EF 6

Upvotes: 3

MKasprzyk
MKasprzyk

Reputation: 499

First qauestion: using Microsoft.EntityFrameworkCore; works well in my project.

Second question: your first way is correct

Third question: If you configure everything like that you don't need to add services.AddEntityFrameworkSqlServer();

Upvotes: -1

Related Questions