Code first DB:
dotnet tool install --global dotnet-ef
dotnet ef migrations add "Initial" -o "Data/Migrations"
dotnet ef database update
ng g c employee --module app --skipTests=true
External libraries:
@angular/material (Angular npm package)
Doing this will trigger the Angular Material command-line setup wizard, which will install the following npm packages: --> npm install xxxxx
@angular/material
@angular/cdk
(prerequisite)
System.Linq.Dynamic.Core (.NET Core NuGet package)
Microsoft.EntityFrameworkCore NuGet package Microsoft.EntityFrameworkCore.Tools NuGet package Microsoft.EntityFrameworkCore.SqlServer NuGet package
If we prefer to do this using the NuGet package manager command line, we can input the following: PM> Install-Package Microsoft.EntityFrameworkCore -Version 5.0.0
PM> Install-Package Microsoft.EntityFrameworkCore.Tools -Version 5.0.0
PM> Install-Package Microsoft.EntityFrameworkCore.SqlServer -Version 5.0.0
1) Create the Entity class
public class Employee
{
public Employee()
{
}
public int Id { get; set; }
public string Name { get; set; }
public string Address { get; set; }
}
2) Create the ApplicationDBContext
public class ApplicationDBContext : DbContext
{
public ApplicationDBContext(): base()
{
}
public ApplicationDBContext(DbContextOptions options) : base(options)
{
}
public DbSet<Employee> Employees { get; set; }
}
3) Add config DB in Memory
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDBContext>(opt => opt.UseInMemoryDatabase("HREmp"));
}
4) Create Controller & Seed data for sample with DB in Memory
[Route("api/[controller]")]
[ApiController]
public class EmployeesController : ControllerBase
{
private readonly ApplicationDBContext _context;
public EmployeesController(ApplicationDBContext context)
{
_context = context;
SeedData();
}
private void SeedData()
{
if (!_context.Employees.Any())
{
_context.Employees.Add(new Employee() { Id = 1, Name = "Jessica Smith", Address = "20 Elm St." });
_context.Employees.Add(new Employee() { Id = 2, Name = "John Smith", Address = "30 Main St." });
_context.Employees.Add(new Employee() { Id = 3, Name = "William Johnson", Address = "100 10th St." });
_context.SaveChanges();
}
}
// GET: api/<ValuesController>
[HttpGet]
public async Task<ActionResult<IEnumerable<Employee>>> GetEmployees() { return await _context.Employees.ToListAsync(); }
}
test API --> localhost .../api/employees
Add format JSON:
Open the Startup.cs file, locate the ConfigureServices method, and add the following code
services.AddControllersWithViews()
.AddJsonOptions(options => {
options.JsonSerializerOptions.WriteIndented = true;
});
5) Fetching and Displaying Data
Create Angular page
ng g c employee --module app --skipTests=true
CREATE src/app/employee/employee.component.html (23 bytes)
CREATE src/app/employee/employee.component.ts (277 bytes)
CREATE src/app/employee/employee.component.css (0 bytes)
UPDATE src/app/app.module.ts (1412 bytes)
EMPLOYEE.TS
Open the /ClientApp/src/app/employees/employee.ts
file and add the following:
export interface Employee {
id: number;
name: string;
address: string;
}
employee.component.ts
import { Component, Inject, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Employee } from './employee';
@Component({
selector: 'app-employees',
templateUrl: './employees.component.html',
styleUrls: ['./employees.component.css']
})
export class EmployeesComponent implements OnInit {
public employees: Employee[];//
constructor(
private http: HttpClient, @Inject('BASE_URL') private baseUrl: string //
) { }
ngOnInit() {
this.http.get<Employee[]>(this.baseUrl + 'api/Employees')
.subscribe(result => {
this.employees = result;
}, error => console.error(error));
}
}
employee.component.html
<h1>employees works!</h1>
<p>Here's a list of employees: feel free to play with it.</p>
<p *ngIf="!employees"><em>Loading...</em></p>
<table class='table table-striped' aria-labelledby="tableLabel" [hidden]="!employees">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr *ngFor="let employee of employees">
<td>{{ employee.id }}</td>
<td>{{ employee.name }}</td>
<td>{{ employee.address }}</td>
</tr>
</tbody>
</table>
employees.component.css
APP.MODULE.TS
Now that we've created the component, we need to add it to the app.module.ts
file (new lines are highlighted):
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';
import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { UploadComponent } from './upload/upload.component';
import { UploadsComponent } from './uploads/uploads.component';
import { EmployeesComponent } from './employees/employees.component';
@NgModule({
declarations: [
AppComponent,
NavMenuComponent,
HomeComponent,
UploadComponent,
UploadsComponent,
EmployeesComponent
],
imports: [
BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
HttpClientModule,
FormsModule,
RouterModule.forRoot([
{ path: '', component: HomeComponent, pathMatch: 'full' },
{ path: 'employees', component: EmployeesComponent },
])
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Menu add:
<li class="nav-item" [routerLinkActive]="['link-active']">
<a class="nav-link text-dark" [routerLink]="['/cities']"
>Cities</a
>
</li>
Serving data with Angular Material
For additional information about Angular Material, check out the following URLs: https://material.angular.io/
https://github.com/angular/components
To install Angular Material, do the following:
- Open Command Prompt.
- Navigate to our project's
/ClientApp/
folder. - Type the following command:
> ng add @angular/material
ReactiveFormsModule
From Solution Explorer, open the /ClientApp/src/app/app.module.ts
file and add the following code (the updated source code is highlighted):
.......
import { ReactiveFormsModule } from '@angular/forms';
@NgModule({
declarations: [
...
],
imports: [
......
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Now that we've added a reference to the ReactiveFormsModule
in our app's AppModule
file, we can implement the Angular component that will host the actual form.