Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is .AddDbContext method?

Tags:

asp.net-core

Everywhere it's said to call services.AddDbContext<> method but it is not recognized inside the ConfigureServices(IServiceCollection services) method.
What am I doing wrong?

like image 589
LINQ2Vodka Avatar asked Mar 04 '17 18:03

LINQ2Vodka


People also ask

What is 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.

Is AddDbContext scoped?

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

What is IDesignTimeDbContextFactory for?

IDesignTimeDbContextFactory<TContext> Interface Implement this interface to enable design-time services for context types that do not have a public default constructor. At design-time, derived DbContext instances can be created in order to enable specific design-time experiences such as Migrations.


1 Answers

You have to reference the correct package first, which depends on the EF Core provider you want to use.

Microsoft.EntityFrameworkCore.SqlServer for SQL Server, Microsoft.EntityFrameworkCore.Sqlite for SQLite and Microsoft.EntityFrameworkCore.InMemory for in memory (only for testing).

These are the official out-of-the-box providers. There are also 3rd party providers for PostgreSQL, MySQL, etc. The documentation providers a list of available 3rd party providers here.

Also depending on the provider you may also need to declare a certain namespace. The built-in providers are declared in Microsoft.Extension.DependencyInjection namespace so you need to add a using Microsoft.Extension.DependencyInjection; to the top of your Startup.cs.

Other providers (Oracle's MySQL provider for example) uses MySQL.Data.EntityFrameworkCore.Extensions namespace, so you need to define this using using MySQL.Data.EntityFrameworkCore.Extensions;

like image 116
Tseng Avatar answered Dec 08 '22 06:12

Tseng