Reputation:
This is how to declare a DB Context according to book "Pro ASP.NET Core MVC 2" , Adam Freeman. What does this parameter mean:
DbContextOptions<ApplicationDbContext> options : base(options) { }
Trying to understand options in declaring DBContext.
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.DependencyInjection;
namespace SportsStore.Models
{
public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options):
base(options)
{
}
public DbSet<Product> Products { get; set; }
}
}
Upvotes: 0
Views: 1454
Reputation: 3348
You have a ApplicationDbContext
that inherits from DbContext
like every database context have to. It represents your database object in code at which you would do CRUD-operations. Because you are inheriting you have the possibility to call the base constructor that does - in that case - the initialization. It could take none or one parameter of type DbContextOptions<T>
or DbContextOptions
in concrete DbContextOptions<ApplicationDbContext>
- that's the base(options)
call. You could find a more detailed and maybe better explanation in this MS doc article base(C# Reference)
The base class' implementation could you find on GitHub - EntityFramework Core repository. (The link is referencing to the base-constructor you are calling in your code.)
The DbContextOptions<ApplicationDbContext>
objects includes the configuration you may have set up before you inject it into your ApplicationDbContext
.
More detailed from MS docs article - Configuring DbContextOptions:
DbContext
must have an instance ofDbContextOptions
in order to perform any work. TheDbContextOptions
instance carries configuration information such as:
- The database provider to use, typically selected by invoking a method such as
UseSqlServer
orUseSqlite
- Any necessary connection string or identifier of the database instance, typically passed as an argument to the provider selection method mentioned above
- Any provider-level optional behavior selectors, typically also chained inside the call to the provider selection method
- Any general EF Core behavior selectors, typically chained after or before the provider selector method
In general DbContextOptions
is a container that includes the whole database context configuration. You could define e.g. if it is a SQL
or in-memory
database and the change tracking behavior too. Link in question's comment already mentioned and in my answer too, the MS doc article will provide the needed information and example.
Upvotes: 1