Take advantage of the DbContext in Entity Framework Core to connect to a database and perform CRUD operations using CLR objects Credit: aitoff Microsoft’s Entity Framework is an open-source object-relational mapper, or ORM, for ADO.Net that helps you isolate the object model of your application from the data model. Entity Framework simplifies data access in your application by allowing you to write code to perform CRUD (Create, Read, Update, and Delete) operations without having to know how the data is persisted in the underlying database. The DbContext acts as a bridge between the domain classes and the database. In this article we will examine how we can configure the DbContext using an instance of DbContextOptions to connect to a database and perform CRUD operations using the Entity Framework Core provider. DbContext explained The DbContext is an integral component of the Entity Framework that represents a connection session with the database. You can take advantage of the DbContext to query data into your entities or save your entities to the underlying database. The DbContext in Entity Framework Core has a number of responsibilities: Managing connections Querying data from the database Saving data to the database Change tracking Caching Transaction management In the sections that follow, we will explore how we can work with the DbContext in ASP.Net Core. Create an ASP.Net Core application in Visual Studio We’ll start by creating an ASP.Net Core application. Note that this post assumes that Visual Studio 2017 is already installed in your system. If you don’t have Visual Studio 2017 installed, you can download a copy here. Then follow these steps to create a new ASP.Net Core project. Launch the Visual Studio 2017 IDE. Click File -> New -> Project. Select the “ASP.Net Core Web Application” project template. Specify the name and location for your project. Click OK. In the “New ASP.Net Core Web Application” dialog window, select .Net Core. Select ASP.Net Core 2.1 from the drop-down list. Select “Web API” as the project template. Ignore the “Enable Docker support” checkbox; we won’t be using Docker here. Ensure that the message “No Authentication” is displayed; we won’t be needing this either. Click OK And that’s it! We will use this application to explore Entity Framework Core in the sections that follow. Create a new DbContext in Entity Framework Core To create a custom Context class, you should extend the DbContext base class in Entity Framework Core as shown below. public class CustomContext : DbContext { public CustomContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { //Write your code here to configure the context } protected override void OnModelCreating(ModelBuilder modelBuilder) { //Write your code here to configure the model } } Refer to the CustomContext class above. Note that it accepts a reference to an instance of the DbContextOptions class. This instance contains the configuration information needed by the DbContext. You can also configure the DbContext using the OnConfiguring method. The OnModelCreating method, which accepts a reference to an instance of the ModelBuilder class as an argument, is used to configure the model. In the DbContext class, you typically have the DbSet properties of entities as shown in the code snippet below. public class CustomContext : DbContext { public CustomContext(DbContextOptions options) : base(options) { } protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { } public DbSet<Author> Authors { get; set; } public DbSet<Blog> Blogs { get; set; } } Register the DbContext with the Entity Framework Core runtime Next, you should register your custom DbContext class as a service in the IServiceCollection via the ConfigureServices method of the Startup class. public void ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion (CompatibilityVersion.Version_2_1); services.AddDbContext<CustomContext>(options => options.UseSqlServer (Configuration.GetConnectionString(“TestConnection”))); } The connection string is obtained using the IConfiguration instance. The AddDbContext extension method is used to register the DbContext as a service. Note how a reference to DbContextOptionsBuilder is used to configure the DbContextOptions. The UseSqlServer extension method is used to register the SQL Server database provider with the Entity Framework Core runtime. Alternatively, you can override the OnConfigure method to register the SQL Server database provider as shown in the code snippet below. protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { if (!optionsBuilder.IsConfigured) { optionsBuilder.UseSqlServer("TestConnection"); } } Use the DbContext with dependency injection To use the custom DbContext we implemented in the controller methods, you should take advantage of dependency injection. The following code snippet illustrates how this can be achieved. public class ValuesController : ControllerBase { private CustomContext dbContext; public ValuesController(CustomContext customContext) { dbContext = customContext; } //Other methods } And that’s all you need to do. You can now leverage the instance of the CustomContext class in your controller methods to perform CRUD operations. The DbContext is conceptually like the ObjectContext. Representing a combination of the unit of work and repository design patterns, the DbContext is responsible for any interaction between the application and the database in use. I’ll discuss additional aspects of Entity Framework Core in future posts here. Related content how-to How to use FastEndpoints in ASP.NET Core Take advantage of the free open-source FastEndpoints library to build fast and lean APIs in your ASP.NET Core applications. By Joydip Kanjilal Jul 11, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Refit to consume APIs in ASP.NET Core Take advantage of Refit REST library to simplify API consumption and make your code cleaner, more efficient, and easier to maintain. By Joydip Kanjilal Jul 04, 2024 10 mins C# Microsoft .NET Software Deployment how-to When to use an abstract class vs. interface in C# Understanding the differences between an abstract class and interface is key to designing loosely coupled and extensible applications. By Joydip Kanjilal Jun 20, 2024 10 mins Small and Medium Business Microsoft .NET C# how-to 6 security best practices for ASP.NET Core Learn the best practices and built-in safeguards for preventing attacks and protecting sensitive data in your ASP.NET Core web applications. By Joydip Kanjilal Jun 07, 2024 6 mins C# Microsoft .NET Web Development Resources Videos