Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding service for EF, AddDbContext or AddEntityFramework

Is there a difference between services.AddDbContext and services.AddEntityFramework().AddDbContext? They booth looks to be valid under core-1.0.0.

Choice A

services.AddDbContext<DbContext>(options => options.UseSqlServer(connection));

Choice B

services.AddEntityFramework()
    .AddDbContext<DbContext>(options =>
        options.UseSqlServer(connection));

Also noticed that .AddSqlServer() looks to be gone. Last time I did some work on core was RC2 and I see that a lot has been cleaned/renamed/simplified, I guess that's nice.

like image 984
Thomas Andreè Wang Avatar asked Jul 22 '16 09:07

Thomas Andreè Wang


People also ask

What is services AddDbContext?

AddDbContext<TContext>(IServiceCollection, Action<DbContextOptionsBuilder>, ServiceLifetime) Registers the given context as a service in the IServiceCollection. You use this method when using dependency injection in your application, such as with ASP.NET.

When would you use EF6 vs EF core?

Keep using EF6 if the data access code is stable and not likely to evolve or need new features. Port to EF Core if the data access code is evolving or if the app needs new features only available in EF Core. Porting to EF Core is also often done for performance.

Which of the below method is used for adding DbContext class as service?

The AddDbContext extension method registers DbContext types with a scoped lifetime by default.


1 Answers

I'm quoting: You only need to use this functionality (AddEntityFramework) when you want Entity Framework to resolve the services it uses from an external IServiceProvider. If you are not using an external IServiceProvider, Entity Framework will take care of creating the services it requires.

See: https://github.com/aspnet/EntityFramework/blob/dev/src/Microsoft.EntityFrameworkCore/Infrastructure/EntityFrameworkServiceCollectionExtensions.cs

I'm quoting: Intentionally in this namespace since this is for use by other relational providers rather than by top-level app developers.

See: https://github.com/aspnet/EntityFramework/blob/94138e66a56693395e5e323a8d4b666bbcb07bf7/src/Microsoft.EntityFrameworkCore/Infrastructure/EntityFrameworkServiceCollectionExtensions.cs

like image 82
enet Avatar answered Nov 24 '22 02:11

enet