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 DispatchProxy for AOP in .NET Core Take advantage of the DispatchProxy class in C# to implement aspect-oriented programming by creating proxies that dynamically intercept method calls. By Joydip Kanjilal Nov 14, 2024 7 mins Microsoft .NET C# Development Libraries and Frameworks news Microsoft’s .NET 9 arrives, with performance, cloud, and AI boosts Cloud-native apps, AI-enabled apps, ASP.NET Core, Aspire, Blazor, MAUI, C#, and F# all get boosts with the latest major rev of the .NET platform. By Paul Krill Nov 12, 2024 4 mins C# Generative AI Microsoft .NET how-to Why use aspect-oriented programming Aspect-oriented programming allows you to isolate the cross-cutting concerns of your application, reduce code duplication, and improve the readability and maintainability of your code. By Joydip Kanjilal Oct 31, 2024 5 mins Microsoft .NET C# Development Libraries and Frameworks how-to How to use Task.WhenEach in .NET 9 Take advantage of the new Task.WhenEach method to process asynchronous tasks as they complete, enhancing the efficiency of your .NET applications. By Joydip Kanjilal Oct 17, 2024 6 mins Microsoft .NET C# Development Libraries and Frameworks Resources Videos