Separation of concern makes our code reusable and easier to manage. In that sense, it is considered a good practice to separate business logic and data handling. MVC pattern is one such implementation that divides an application into three major parts (model, view, and controller). In this writing, we will use Entity Framework to implement the MVC pattern in the .NET application
Project Configurations
Creating a Project with MVC Structure
Installing Packages
We need packages to connect our project to a database. Open the search bar at the top then find NuGet Gallery
NuGet: Open NuGet Gallery
▶ Packages needed
When installing a package, The version of the package must match the version of .NET you are using. For example, if you are using .NET 7 you should download packages that start with 7.
Search each of the packages below and check the check box beside the project that will deal with data handling (here the Infrastructure folder) and click 'install'. This package allows us to use the SQLite database.
Microsoft.EntityFrameworkCore.Sqlite
This package is for converting our code to a database. Add this to the API folder
Microsoft.EntityFrameworkCore.Design
This package is for data migration. Add this to the API folder
dotnet-ef
Creating Model
Create a folder to hold the entity in the core folder
Add an entity class
Creating Context
Create a folder to hold the context in the infrastructure folder
Add a context class
Inherit from the 'DbContext' class
Add the entity as a property
using Core.Entities;
using Microsoft.EntityFrameworkCore;
namespace Infrastructure.Data
{
public class StoreContext : DbContext
{
public StoreContext(DbContextOptions options) : base(options)
{
}
public DbSet<Item> Items { get; set; }
}
}
Context Registration as a Service
Migration
Creating a DB
Creating Controller
Add a controller class in the API folder
Inherit from the 'ControllerBase' class
Then, add decorators to easily set up controllers
[ApiController]
[Route("[controller]")]
Add a constructor and inject the context class
private readonly StoreContext _context;
public StoreController(StoreContext context)
{
this._context = context;
}
How to Use
We can access the database with the context class injected in the controller class. For example, we can get all the items with the code below
[HttpGet]
public ActionResult<List<Item>> GetItems()
{
return _context.Items.ToList();
}
In this writing, we have seen how we can use the MVC pattern in .NET with EntityFramework
References
https://www.tutorialspoint.com/design_pattern/mvc_pattern.htm
'Backend > .NET' 카테고리의 다른 글
Adding Configurations When Creating a Database (2) | 2023.03.31 |
---|---|
Application Architecture - Repository (0) | 2023.03.30 |
.NET - Cleaning Up Program File: Service Extension Method (0) | 2023.03.08 |
How to create .NET web-API (1) | 2023.03.02 |
Adding Relation to DB (0) | 2023.03.02 |