The instance of the DbContext class represents the session to the database and this DbContext class does most of the heavy lifting of your data access for your application. Create a new class named EmployeeDbContext with the following content:
Go to https://goo.gl/hbju3w to access the code.
using Microsoft.EntityFrameworkCore;
namespace ConsoleEF
{
public class EmployeeDbContext : DbContext
{
public DbSet<Employee> Employees { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Data Source=
(localdb)\MSSQLLocalDB;Initial Catalog=
EFConsole;Integrated Security=True;Connect
Timeout=30;
Encrypt=False;TrustServerCertificate=True;
ApplicationIntent=ReadWrite;
MultiSubnetFailover=False");
}
}
There are a few things to be noted in the preceding code snippet:
- Include the Microsoft.EntityFrameworkCore namespace as the DbContext class available in this namespace. Our connection string is currently hardcoded but we can easily make it configurable.
- In order to use the DbContext API, a class has to be created that inherits from the DbContext class so that we can access methods of the DbContext API. We have created the EmployeeDbContext class, which was inherited from DbContext class.
- DbSet is a class that allows operations of Entity Framework to be performed for a given Entity type. We need to create the DbSet object for each of the Entity types that we use in our application. In this example, we are using only one DbSet object as we are working with the Employee class.