How to make Controller Based ASP.NET Core .Net 6 API on Visual Studio Code part 2
On the previous lesson we’ve created API project called learn, so on this lesson we will add controller and models to our API. Please see the part 1 before continue.
Step 1 : Add neccesary package
Enter the following command on your console to add the package :
#mySql connection
dotnet add package Pomelo.EntityFrameworkCore.MySql -v 6.0.3
#scaffold package
dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design -v 6.0.17
dotnet add package Microsoft.EntityFrameworkCore.Design -v 6.0.33
dotnet add package Microsoft.EntityFrameworkCore.SqlServer -v 6.0.33
dotnet add package Microsoft.EntityFrameworkCore.Tools -v 6.0.33
#install scaffold
dotnet tool install -g dotnet-aspnet-codegenerator --version 6This will add MySQL and some package in our project to use scaffold and also install the scaffold engine.
Step 2 : Add model class
a. On your project create new folder and named it Models and create new file named User.cs. The current project should look like this :
b. On the User.cs create class that represent your table.
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace learn.Models;
[Table("user")]
public class User
{
public int Id {get; set;}
[Required]
public string Username {get; set;} = null!;
[Required]
public string Name {get; set;} = null!;
[Required]
public string Email {get; set;} = null!;
[Required]
public string Password {get; set;} = null!;
[Column("created_at")]
public DateTime CreatedAt {get; set;}
[Column("created_by")]
public int CreatedBy {get; set;}
[Column("updated_at")]
public DateTime? UpdateAt {get; set;}
[Column("updated_by")]
public int? UpdatedBy {get; set;}
[Column("is_delete")]
public bool IsDelete {get; set;}
}Let’s break down the code.
public int Id {get; set;}public int Id : This line of code is used to create public property named Id on User class with the type of Integer.get : allows other code to read the value.set : allows other code to set the value.
[Required]
public string Username {get; set;} = null!;[Required] : Used to tell that the username property must have a value.= null! : This is used to initializes the property to null and ! is used to ignored the null warning. I’m not sure about this actually 😅
[Column("updated_by")]
public int? UpdatedBy {get; set;}[Column(“updated_by”)] : To point the column name on the Database. This is useful when you wanna give different name between the property and the database column.int? : The ? is use to tell that the property is nullable (accept null value)
Step 3: Add database context
a. Create new file named LearnContext.cs in the Models folder, so the current folder will be like this :
b. Write the following code to LearnContext.cs :
using Microsoft.EntityFrameworkCore;
namespace learn.Models;
public class LearnContext : DbContext
{
public LearnContext(DbContextOptions<LearnContext> options)
: base(options)
{
}
public DbSet<User> Users { get; set; } = null!;
}This code is use to register user model to our API and also a connector between model and the database. Here is the explanation :
public class LearnContext : DbContextClass LearnContext inherit the DbContext as a core class for communicate to the database.
public LearnContext(DbContextOptions<LearnContext> options)
: base(options)
{
}Create constructor of class LearnContext with options property as database configuration. In our code, we’re not add any configuration so leave it as blank constructor {}
public DbSet<User> Users { get; set; } = null!;This method is use to represent the user database from the database with the name of Users. The null! is use as null forgiving which is meant that you confident that your data is not null.
Step 4 : Register the database context
After successfully create database context, next step is to register it to your API.
Get Donny’s stories in your inbox
Join Medium for free to get updates from this writer.
a. Open the program.cs and add this code :
// Register LearnContext to the API
builder.Services.AddDbContext<LearnContext>(options =>
{
var connectionString = builder.Configuration.GetConnectionString("learnDatabase");
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});What this code do is to get the connection string with the name of learnDatabase from appsetting.Development.json and use it to make database connection using useMySql method. And don’t forget to import the library in the top of the class :
using learn.Models;
using Microsoft.EntityFrameworkCore;After you add the code, the program.cs will looks like this :
using learn.Models;
using Microsoft.EntityFrameworkCore;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
// Register LearnContext to the API
builder.Services.AddDbContext<LearnContext>(options =>
{
var connectionString = builder.Configuration.GetConnectionString("learnDatabase");
options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();b. Add the connection string to appsettings.Development.json so the API can connect to the database server :
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
"learnDatabase" : "Server=localhost;Port=3306;Username=root;Password=;Database=learn;"
}
}the string can be different, it will depends on your local server setting.
Step 5 : Add Controller using Scaffold
The last step is to create the controller in our API. Controller can be create manually but in this tutorial we will create it using scaffold which is more easy to create. Enter this command in your console to create controller using scaffold :
dotnet aspnet-codegenerator controller -name UserController -async -api -m User -dc LearnContext -outDir ControllersWhat this command do is :dotnet aspnet-codegenerator controller : generate controller code in our API-name UserController : options for controller name -async : options to create async controller-api : options to create REST style API, which means no view is assumed-m User : options to tell which model is used for the controller-dc LearnContext : tell which context class is used-outDir Controllers : output folder for created controller
After successfully run the command, new UserController will be created inside controllers folder. Now we can delete WeatherController and WeatherForecast file.
Run the program using F5 and the opened browser will looks like this
Congratulations your API have controller and model now 🎉
You can customize this API and add other feature like JWT authentication, password encryption, etc.





