Creating the Database Context definition c# dbcontext entity-framework-core


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): 

         public DbSet<Product> Products { get; set; }
3/27/2018 7:14:54 AM

Accepted Answer

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 of DbContextOptions in order to perform any work. The DbContextOptions instance carries configuration information such as:

  • The database provider to use, typically selected by invoking a method such as UseSqlServer or UseSqlite
  • 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.

3/27/2018 7:39:33 AM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow