Build and ASP.net core App and angular from scratch 2 — Creating our First Entity.

Khemlall Mangal
7 min readJul 17, 2022

Alright let start creating our API user entity. Here is the goal for part1 and 2..

Learning Goals:

  • Using dotnet CLI
  • Api Controllers and Endpoints
  • Entity Framework
  • Api Project Structure
  • Configuration and Environment Variable
  • Source Control
  1. Create a folder called Entities → then create a class call AppUser.cs
  2. (tip) use the prop keyword and then Tab — this will create property.

A couple of other thing to point out. We are using the short hand version of the property when we are getting and setting property so then can be getted and setted from other classes in our application. They have an access setting… this is our Public also refer to as(access modifier) which mean that this property can be get or set from any other class in our application. There is also PROTECTED access modifier. This property can be access from this class or any class that inherit from this class. We have private access modifier which means this property is only accessible from inside this class itself.

Alright, i just give you a quick lesson is C# about class and access modifiers as we are building our application. This way if you are new to programming you will learn as you proceed.

Lets discuss Entity Framework. An object relational Mapper (ORM). It translates our code into SQL commands that update our tables in the database

Entity Framework Intro

Entity Framework allow us to:

a) Allows us to query our database using linq query
b) Change tracking, keep track of changes occuring in our entities
c) Save our database, dbcontext class give us save chnages method we can use
d) optimistic concurrency
e) automatic transaction management while querying or saving data.
f) first level caching out of the box, so repeated querying will return data from the cache instead of hitting the database
g) Built in Conventions
h) configuration
i) Migration — gives us the ability to create a database schema so when we start our application ,we can automatically generate our database in our database server.

We will be touching on each of these with example as we continue.

Install Entity Framework

  1. Go to your extention and install nuget gallery

2. CTRL + SHIFT + P

3- Search for nuget and select open nuget gallery and search for microsoft entity frameworkCore and we will use sqllite as our database which is not for production but we will change this when we will deploy to production later.

install the version you have install in your project (sdk) ad check the api.csproj and click install.

If you go now to our API csproj file you will notice that we have a new entry for entity framework.

Creating DBCONTEXT class

Let create this very important class that acts as the bridge between our database and our code that access the database and that the dbcontext class.

  1. Create a New Folder under API called Data
  2. Create a class call DataContext.cs
  1. Enter the following code:
using System;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Entities;
using Microsoft.EntityFrameworkCore;
namespace API.Data
{
public class DataContext : DbContext
{
public DataContext(DbContextOptions options) : base(options)
{
}
public DbSet<AppUser> Users { get; set; }
}
}

In our start up class under configureservices let add:

services.AddDbContext<DataContext>(options => 
{
options.UseSqlite("connection string"); (place holder for now)
});

Now lets talk about Creating our Connection string. Navigate to appsettings development.json file and connection string exactly as we have it here for example.

Next lets go back to our startup class and lets change it up a little and add the following code:

Update the start up class

public class Startup
{
private readonly IConfiguration _config;
public Startup(IConfiguration config)
{
_config = config;

}
// public IConfiguration Configuration { get; }// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<DataContext>(options =>
{
options.UseSqlite("connection string");
});
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "API", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "API v1"));
}
app.UseHttpsRedirection();app.UseRouting();app.UseAuthorization();app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
}

Now lets update the hardcoded string we add for connection string, lets update:

Code

options.UseSqlite(_config.GetConnectionString("DefaultConnection"));

Alright, next we need to install a tool base on the version of sdk you installed. i installed 5.0.0

dotnet tool install — global dotnet-ef — version 5.0.0.. Go to nugetgaller.org and find the dotnet-ef tool for the version you have.

Let create our database migration to create database schema or code to create a database base on our code that we have written so far.

First lets go to ctrl + shift + p and open nuget gallery, search for Microsoft.EntityFrameworkCore.Design and install the package.

Next stop your project if it is running and then pass the following command:

dotnet ef migrations add InitialCreate -o Data/Migrations

Once successful you should see the migration folder created with our class:

Next is Create the Database.

Run the following command:

dotnet ef database update

Now in your extension, install sqlite

ctrl + shift +p -> open database and choose the database we created. We will pick up from here in the next session. Stay tune.

Now that we have this installed, lets create some data and then later on we will do this in a more efficient way.

You should see sqlite explorer added to your IDE:

Right click on user → New query insert → enter a few record.

Example

-- SQLiteINSERT INTO Users (Id, UserName)VALUES (1, "RMANGAL");

Once you created and right click and show table you should see the new records in the table.

Ok now we are ready to create our own API controller.

Let create a controller call UsersController. We create a get request to get all the user data and a get request to get by specific ID.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using API.Data;
using API.Entities;
using Microsoft.AspNetCore.Mvc;
namespace API.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class UsersController : ControllerBase
{
private readonly DataContext _context;
public UsersController(DataContext context)
{
_context = context;
}
[HttpGet]
public ActionResult<IEnumerable<AppUser>> GetUsers()
{
var users = _context.Users.ToList();
return users;
}
[HttpGet("{id}")]
public ActionResult<AppUser> GetUser(int id)
{
return _context.Users.Find(id);

}
}
}

In postman, or you can go to swagger : https://localhost:5001/swagger/index.html and see the new api.

Lets create a Collection and then lets add our getUsers request to verify our response.

sample getusers request on postman

Send a get request to : https://localhost:5001/api/users and you should now see the data you just added to your database displaying.

Now lets make our code Asynchronous. Allowing multiple thread to work on each request to make it more scalable. If you are making a database call, make it asynchronous.

code

[HttpGet]
public async Task< ActionResult<IEnumerable<AppUser>>> GetUsers()
{
return await _context.Users.ToListAsync();
}
[HttpGet("{id}")]public async Task<ActionResult<AppUser>> GetUser(int id){return await _context.Users.FindAsync(id)}

Lets save our code into source control.

--

--

Khemlall Mangal

I am a passionate coder, QA Engineer, and someone who enjoys the outdoors.