EF Core in .NET 7 API

What is Entity Framework (EF) Core?

The Entity Framework (EF) Core is a lightweight, extensible, open-source, and cross-platform version of the popular Entity Framework data access technology.

In this article, we'll be diving into the Code First approach in EF Core with a .NET 7 API. This methodology starts with defining your model classes first; then, EF Core creates the database and its structure based on these models.

Why do we need EF Core?

EF Core is an open-source lightweight ORM developed by Microsoft which provides a way to interact with relational databases using programming concepts. Here are some of the points why it is beneficial 

  • Object-Relational Mapping: EF Core bridges the gap between relational databases and object-oriented programming. It reduces the boilerplate code that we have to write in order to map database tables and columns into object properties. EF Core does this automatically.
  • LINQ: Language Integrated Query (LINQ) is a powerful querying language that comes with .NET. It allows developers to write database queries in a C# familiar syntax. LINQ translates the queries we write in C# into efficient database queries.
  • Testability: EF Core's design promotes testability by allowing developers to mock or replace the database context during unit testing. This enables developers to write isolated tests without relying on a physical database, making the testing process more efficient and reliable.

Let's begin

We will create a new project.

EF Core in .NET 7 API

EF Core in .NET 7 API

EF Core in .NET 7 API

After project creation, we will have a structure like this.

EF Core in .NET 7 API

Next, we will install the required nuget packages.

EF Core in .NET 7 API

Install the following packages,

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.Design
  • Microsoft.EntityFrameworkCore.SqlServer

Now we will create a folder called 'Models' in the solution, and inside it, we will add another folder called Entities which will have entity classes from which our database will be created.

We will create a class "Department.cs" with the following properties.

    public class Department
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Description { get; set; }
        public bool IsActive { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }

Now we will create a class called "Employee.cs".

    public class Employee
    {
        public int Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int DepartmentId { get; set; }

        public bool IsActive { get; set; }
        public DateTime CreatedDate { get; set; }
        public DateTime UpdatedDate { get; set; }
    }

Now we will create an "EmployeeDbContext.cs".

    public class EmployeeDbContext : DbContext
    {
        public EmployeeDbContext(DbContextOptions<EmployeeDbContext> options) : base(options) 
        {
        }

        public DbSet<Department> Departments { get; set; }
        public DbSet<Employee> Employees { get; set; }
    }

As we can see, this EmployeeDbContext class extends from the DbContext class that comes in the "Microsoft.EntityFrameworkCore" framework, and then we have the DbSets for the Departments and Employees as per the entities we created.

Now we will configure the DB context in the "Program.cs".

We will add the following code.

builder.Services.AddDbContext<EmployeeDbContext>(options =>
{
    options.UseSqlServer("Server=RAVI;Database=EFCoreCodeFirstDB;Trusted_Connection=True;MultipleActiveResultSets=true;TrustServerCertificate=True;");
});

After that, we will run the migrations commands that will help us maintain the DB state.

Run the following command in the solution directory.

“dotnet ef migrations add InitialCreate”.

After running it, the output will look something like this.

EF Core in .NET 7 API

In the solution explorer, you will see the following folder.

EF Core in .NET 7 API

 

Note. If the above command throws the error, please run the following command first.

“dotnet tool install --global dotnet-ef”

After this, we will run the following command.

“dotnet ef database update”

You should see the following output.

EF Core in .NET 7 API

After this, you can see your SqlServer to see that your database has been created along with your tables.

EF Core in .NET 7 API

Now we will add a controller called "DepartmentController.cs".

[Route("api/[controller]")]
[ApiController]
public class DepartmentController: ControllerBase {
  private readonly EmployeeDbContext _dbContext;
  public DepartmentController(EmployeeDbContext dbContext) {
    _dbContext = dbContext;
  }

  [HttpGet]
  public IActionResult Get() {
    var departments = _dbContext.Departments.ToList();
    return Ok(departments);
  }

  [HttpPost]
  public IActionResult Post([FromBody] Department department) {
    _dbContext.Departments.Add(department);
    _dbContext.SaveChanges();
    return Ok();
  }

  [HttpPut]
  public IActionResult Put([FromBody] Department department) {
    var dept = _dbContext.Departments.FirstOrDefault(d => d.Id == department.Id);
    if (dept == null)
      return NotFound();

    dept.Name = department.Name;
    dept.Description = department.Description;
    dept.UpdatedDate = DateTime.Now;
    _dbContext.SaveChanges();
    return Ok(dept);
  }
}

In our DepartmentController.cs, we have three REST endpoints; one is HttpGet which will get us the list of all departments. The second endpoint is HTTP POST which will save the departments in the DB, and the last one is HTTPPUT which will update the department in the DB.

Similarly, we will have an employee controller as well, which will save, update and get employees.

[Route("api/[controller]")]
[ApiController]
public class EmployeeController: ControllerBase {
  private readonly EmployeeDbContext _dbContext;
  public EmployeeController(EmployeeDbContext dbContext) {
    _dbContext = dbContext;
  }

  [HttpGet]
  public IActionResult Get() {
    var employees = _dbContext.Employees.ToList();
    return Ok(employees);
  }

  [HttpPost]
  public IActionResult Add([FromBody] Employee employee) {
    _dbContext.Employees.Add(employee);
    _dbContext.SaveChanges();
    return Ok();
  }

  [HttpPut]
  public IActionResult Update([FromBody] Employee employee) {
    var emp = _dbContext.Employees.FirstOrDefault(d => d.Id == employee.Id);
    if (emp == null)
      return NotFound();

    emp.FirstName = employee.FirstName;
    emp.LastName = employee.LastName;
    emp.DepartmentId = employee.DepartmentId;
    emp.UpdatedDate = DateTime.Now;
    _dbContext.SaveChanges();
    return Ok(emp);
  }
}

Now let's run our API, and then we will hit the POST endpoint of the department's controller.

EF Core in .NET 7 API

 

Now we will try to get all the departments by hitting the Get endpoint of departments.

EF Core in .NET 7 API

 

Now we will create a new employee using the Post endpoint of the employee controller.

EF Core in .NET 7 API

 

Now we will hit the Get endpoint of the employee controller.

EF Core in .NET 7 API

 

Now we can verify the same values from the database as well.

EF Core in .NET 7 API

 

As we can verify, our values are stored in the database as well.

Summary

We have seen how to create a .NET 7 API and use EF Core to interact with the relational database to store and get the data.

If you wish to see the code, please click here!

Happy Coding!


Similar Articles