ASP.NET Core Angular 2 EF 1.0.1 Web API Using Template Pack

ASP.NET Core Angular 2 EF 1.0.1 Web API Using Template Pack.

Framework

Introduction

In this article let’s see how to create our first ASP.NET Core Angular 2 Starter Application (.NET Core) using Template pack using Entity Framework 1.0.1 and Web API to display data from the database to our Angular2 and ASP.NET Core web application.

Note

Kindly read our previous article which explains  in depth about Getting Started With ASP.NET Core Template Pack

In this article we will see about:

  • Creating sample Database and Table in SQL Server to display in our web application.
  • How to create ASP.NET Core Angular 2 Starter Application (.NET Core) using Template pack
  • Creating EF, DBContext Class and Model Class.
  • Creating WEB API
  • Creating our First Component TypeScript file to get WEB API JSON result using Http Module.
  • Creating our first Component HTML file to bind final result.

Prerequisites

Make sure you have installed all the prerequisites in your computer. If not, then download and install all of them, one by one.

  1. First, download and install Visual Studio 2015 with Update 3 from this link.
  2. If you have Visual Studio 2015 and have not yet updated with update 3, download and install the Visual Studio 2015 Update 3 from this link.
  3. Download and install .NET Core 1.0.1
  4. Download and install TypeScript 2.0
  5. Download and install Node.js v4.0 or above. I have installed V6.9.1 (Download link).
  6. Download and install Download ASP.NET Core Template Pack visz file from this link.

Code Part

Step 1 Create a Database and Table

We will be using our SQL Server database for our WEB API and EF. First, we create a database named StudentsDB and a table as StudentMaster. Here is the SQL script to create Database table and sample record insert query in our table. Run the below query in your local SQL server to create Database and Table to be used in our project.

  1. USEMASTER  
  2. GO  
  3. --1) Check  
  4. for the Database Exists.If the database is exist then drop and create new DB  
  5. IFEXISTS(SELECT[name] FROMsys.databasesWHERE[name] = 'StudentsDB')  
  6. DROPDATABASEStudentsDB  
  7. GO  
  8. CREATEDATABASEStudentsDB  
  9. GO  
  10. USEStudentsDB  
  11. GO  
  12. --1) //////////// StudentMasters  
  13. IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentMasters')  
  14. DROPTABLEStudentMasters  
  15. GO  
  16. CREATETABLE[dbo].[StudentMasters](  
  17.         [StdID] INTIDENTITYPRIMARYKEY, [StdName][varchar](100) NOTNULL, [Email][varchar](100) NOTNULL, [Phone][varchar](20) NOTNULL, [Address][varchar](200) NOTNULL  
  18.     )  
  19.     --insert sample data to Student Master table  
  20. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  21. VALUES('Shanu''syedshanumcain@gmail.com''01030550007''Madurai,India')  
  22. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  23. VALUES('Afraz''Afraz@afrazmail.com''01030550006''Madurai,India')  
  24. INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
  25. VALUES('Afreen''Afreen@afreenmail.com''01030550005''Madurai,India')  
  26. select * from[StudentMasters]  
Step 2 Create ASP.NET Core Angular 2 application

After installing all the prerequisites listed above and ASP.NET Core Template, click Start >> Programs >> Visual Studio 2015 >> Visual Studio 2015, on your desktop. Click New >> Project. Select Web >> ASP.NET Core Angular 2 Starter. Enter your project name and click OK.

Framework

After creating ASP.NET Core Angular 2 application, wait for a few seconds. You will see that all the dependencies are automatically restoring.

Framework

What is new in ASP.NET Core Template Pack Solution?

Framework
 
  1. WWWroot

    We can see all the CSS,JS files are added under the “dist” folder .”main-client.js” file is the important file as all the Angular2 results will be compiled and results will be loaded from this “js” file to our html file.

    Framework

  2. ClientApp Folder

    We can see a new folder Client App inside our project solution. This folder contains all Angular2 related applications like Modules, Components and etc. We can add all our Angular 2 related Modules, Component, Template, and HTML files  under this folder. We can see in detail about how to create our own Angular2 application here, below, in our article.

    In Components folder under app folder we can see many subfolders like app. counter, fetchdata, home and navmenu. By default, all this sample applications have  been created and when we run our application we can see all the sample Angular2 application results.

    Framework

    When we run the application, we can see navigation in the left side and the right side contains data. All the Angular2 samples will be loaded from the above folder.

    Framework

  3. Controllers Folder

    This is our MVC Controller folder, we can create both MVC and Web API Controllers in this folder.

  4. View Folder

    This is our MVC View folder.

  5. Other Important files

    We can also see other important ASP.NET Core files like

    • project.json
      ASP.NET Core dependency list can be found in this file. We will be adding our Entity framework in the dependency section of this file.
    • package.json
      This is another important file as all Angular2 related dependency lists will be added here. By default all the Angular2 related dependencies have been added here in ASP.NET Core Template pack.
    • appsettings.json
      We can add our database connection string in this appsetting.json file.

We will be using all this in our project to create, build, and run our Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1

Step 3 Creating Entity Framework

Add Entity Framework Packages

To add our Entity Framework Packages in our ASP.NET Core application, open the Project.JSON File and in dependencies add the below line.

Note Here we have used EF version 1.0.1.

  1. "Microsoft.EntityFrameworkCore.SqlServer""1.0.1",  
  2. "Microsoft.EntityFrameworkCore.Tools""1.0.0-preview2-final"  
Framework

When we save the project,.json file we can see the reference is restored.

Framework

After few second we can see Entity framework package has been restored and all references have been added.

Framework

Adding Connection String

To add the connection string with our SQL connection open the “appsettings.json” file .Yes this is the JSON file and this file looks like the below image by default.

Framework

In this appsettings.json file add our connection string
  1. "ConnectionStrings": {  
  2.     "DefaultConnection""Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"  
  3. },  
Note

Change the SQL connection string as per your local connection.

Framework

Next step is we create a folder named “Data” to create our model and DBContext class.

Framework

Creating Model Class for Student

We can create a model by adding a new class file in our DataFolder. Right Click Data folder and click Add>Click Class. Enter the class name as StudentMasters and click Add.

Framework

Now in this class we first create property variable, and add student. We will be using this in our WEB API controller.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingSystem.ComponentModel.DataAnnotations;  
  6. namespace Angular2ASPCORE.Data {  
  7.     publicclassStudentMasters {  
  8.         [Key]  
  9.         publicintStdID {  
  10.             get;  
  11.             set;  
  12.         }  
  13.         [Required]  
  14.         [Display(Name = "Name")]  
  15.         publicstringStdName {  
  16.             get;  
  17.             set;  
  18.         }  
  19.         [Required]  
  20.         [Display(Name = "Email")]  
  21.         publicstring Email {  
  22.             get;  
  23.             set;  
  24.         }  
  25.         [Required]  
  26.         [Display(Name = "Phone")]  
  27.         publicstring Phone {  
  28.             get;  
  29.             set;  
  30.         }  
  31.         publicstring Address {  
  32.             get;  
  33.             set;  
  34.         }  
  35.     }  
  36. }  
Creating Database Context

DBContextis Entity Framework Class for establishing connection to database.

We can create a DBContext class by adding a new class file in our Data Folder. Right Click Data folder and click Add>Click Class. Enter the class name as StudentContext and click Add.

Framework

In this class we inherit DbContext and created Dbset for our students table.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingMicrosoft.EntityFrameworkCore;  
  6.   
  7. namespace Angular2ASPCORE.Data {  
  8.     publicclassstudentContext: DbContext {  
  9.         publicstudentContext(DbContextOptions < studentContext > options): base(options) {}  
  10.         publicstudentContext() {}  
  11.         publicDbSet < StudentMasters > StudentMasters {  
  12.             get;  
  13.             set;  
  14.         }  
  15.     }  
  16. }  
Startup.CS

Now we need to add our database connection string and provider as SQL SERVER.To add this we add the below code in Startup.cs file under ConfigureServices method.

// Add Entity framework .
  1. services.AddDbContext < studentContext > (options =>  
  2.     options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));  
Step 4 Creating Web API

To create our WEB API Controller, right click Controllers folder. Click Add and click New Item.

Framework

Click ASP.NET in right side > Click Web API Controller Class. Enter the name as “StudentMastersAPI.cs” and click Add.

Framework

In this we are using only the Get method to get all the student results from the database and bind the final result using Angular2 to html file.

Here in web API Class only add the get method to get all the student details. Here is the code to get all student results using WEB API.
  1. using System;  
  2. usingSystem.Collections.Generic;  
  3. usingSystem.Linq;  
  4. usingSystem.Threading.Tasks;  
  5. usingMicrosoft.AspNetCore.Mvc;  
  6. using Angular2ASPCORE.Data;  
  7. usingMicrosoft.EntityFrameworkCore;  
  8. usingMicrosoft.AspNetCore.Http;  
  9. // For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860  
  10.   
  11. namespace Angular2ASPCORE.Controllers {  
  12.     [Produces("application/json")]  
  13.     [Route("api/StudentMastersAPI")]  
  14.     publicclassStudentMastersAPI: Controller {  
  15.         privatereadonlystudentContext _context;  
  16.   
  17.         publicStudentMastersAPI(studentContext context) {  
  18.             _context = context;  
  19.         }  
  20.   
  21.         // GET: api/values  
  22.   
  23.         [HttpGet]  
  24.         [Route("Student")]  
  25.         publicIEnumerable < StudentMasters > GetStudentMasters() {  
  26.             return _context.StudentMasters;  
  27.   
  28.         }  
  29.   
  30.     }  
  31. }  
To test it we can run our project and copy the get method api path; here we can see our API path for get is api/StudentMastersAPI/Student

Run the program and paste the above API path to test our output.

Framework

Working with Angular2

We create all Angular2 related Apps, Modules, Services, Components and html templates under ClientApp/App folder.

We create “students” folder under app folder to create our typescript and html file for displaying Student details.

Framework

Step 5 Creating our First Component TypeScript

Right Click on student folder and click on add new Item. Select Client-side from left side and select TypeScript File and name the file “students.component.ts” and click Add.

Framework

In students.component.ts file we have three parts:
  1. import part
  2. component part
  3. class for writing our business logics.

First we import Angular files to be used in our component --  here we import http for using http client in our Angular2 component.

In component we have selector and template. Selector is to give a name for this app and in our html file we use this selector name to display in our html page.

In template we give our output html file name Here we will create an html file as “students.component.html”.

Export Class is the main class where we do all our business logic and variable declaration to be used in our component template. In this class we get the API method result and bind the result to the student array.

  1. import {  
  2.     Component  
  3. } from '@angular/core';  
  4. import {  
  5.     Http  
  6. } from "@angular/http";  
  7. @Component({  
  8.     selector: 'students',  
  9.     template: require('./students.component.html')  
  10. })  
  11.   
  12. exportclassstudentsComponent {  
  13.     public student: StudentMasters[] = [];  
  14.     myName: string;  
  15.     constructor(http: Http) {  
  16.         this.myName = "Shanu";  
  17.         http.get('/api/StudentMastersAPI/Student').subscribe(result => {  
  18.             this.student = result.json();  
  19.         });  
  20.     }  
  21. }  
  22. exportinterfaceStudentMasters {  
  23.     stdID: number;  
  24.     stdName: string;  
  25.     email: string;  
  26.     phone: string;  
  27.     address: string;  
  28. }  
Step 6 Creating our First Component HTML File

Right Click on student folder and click on add new Item. Select Client-side from left side and select html File and name the file as “students.component.html” and click Add.

Framework

Write the below html code to bind the result in our html page
  1. <h1>Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1 </h1>  
  2. <hr/>  
  3. <h2>My Name is : {{myName}}</h2>  
  4. <hr/>  
  5. <h1>Students Details :</h1>  
  6. <p*ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>  
  7.     <tableclass='table' style="background-color:#FFFFFF; border:2px#6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">  
  8.         <trstyle="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid1px#659EC7;">  
  9.             <tdwidth="100" align="center">Student ID</td>  
  10.                 <tdwidth="240" align="center">Student Name</td>  
  11.                     <tdwidth="240" align="center">Email</td>  
  12.                         <tdwidth="120" align="center">Phone</td>  
  13.                             <tdwidth="340" align="center">Address</td>  
  14.                                 </tr>  
  15.                                 <tbody*ngFor="let StudentMasters of student">  
  16.                                     <tr>  
  17.                                         <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  18.                                             <spanstyle="color:#9F000F">{{StudentMasters.stdID}}</span>  
  19.                                                 </td>  
  20.                                                 <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  21.                                                     <spanstyle="color:#9F000F">{{StudentMasters.stdName}}</span>  
  22.                                                         </td>  
  23.                                                         <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  24.                                                             <spanstyle="color:#9F000F">{{StudentMasters.email}}</span>  
  25.                                                                 </td>  
  26.                                                                 <tdalign="center" style="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  27.                                                                     <spanstyle="color:#9F000F">{{StudentMasters.phone}}</span>  
  28.                                                                         </td>  
  29.                                                                         <tdstyle="border: solid1px#659EC7; padding: 5px;table-layout:fixed;">  
  30.                                                                             <spanstyle="color:#9F000F">{{StudentMasters.address}}</span>  
  31.                                                                                 </td>  
  32.                                     </tr>  
  33.                                     </tbody>  
  34.                                     </table>  
Step 7 Adding Students Navigation menu

We can add our newly created student details menu in the existing menu.

To add our new navigation menu open the “navmenu.component.html” under navmenumenu.write the below code to add our navigation menu link for students.
  1. <li[routerLinkActive]="['link-active']">  
  2.     <a[routerLink]="['/students']">  
  3.         <spanclass='glyphiconglyphicon-th-list'>  
  4.             </span> Students  
  5.             </a>  
  6.             </li>  
Framework

Step 8 App Module

App Module is the root for all files and we can find the app.module.ts under ClientApp\app, and import our students component
  1. import {  
  2.     studentsComponent  
  3. } from './components/students/students.component';  
  4. Next in @NGModule add studentsComponent  
  5. In routing add our students path.  
  6. The code will be looks like this  
  7. import {  
  8.     NgModule  
  9. } from '@angular/core';  
  10. import {  
  11.     RouterModule  
  12. } from '@angular/router';  
  13. import {  
  14.     UniversalModule  
  15. } from 'angular2-universal';  
  16. import {  
  17.     AppComponent  
  18. } from './components/app/app.component'  
  19. import {  
  20.     NavMenuComponent  
  21. } from './components/navmenu/navmenu.component';  
  22. import {  
  23.     HomeComponent  
  24. } from './components/home/home.component';  
  25. import {  
  26.     FetchDataComponent  
  27. } from './components/fetchdata/fetchdata.component';  
  28. import {  
  29.     CounterComponent  
  30. } from './components/counter/counter.component';  
  31. import {  
  32.     studentsComponent  
  33. } from './components/students/students.component';  
  34.   
  35. @NgModule({  
  36.     bootstrap: [AppComponent],  
  37.     declarations: [  
  38.         AppComponent,  
  39.         NavMenuComponent,  
  40.         CounterComponent,  
  41.         FetchDataComponent,  
  42.         HomeComponent,  
  43.         studentsComponent  
  44.     ],  
  45.     imports: [  
  46.         UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.  
  47.         RouterModule.forRoot([{  
  48.             path: '',  
  49.             redirectTo: 'home',  
  50.             pathMatch: 'full'  
  51.         }, {  
  52.             path: 'home',  
  53.             component: HomeComponent  
  54.         }, {  
  55.             path: 'counter',  
  56.             component: CounterComponent  
  57.         }, {  
  58.             path: 'fetch-data',  
  59.             component: FetchDataComponent  
  60.         }, {  
  61.             path: 'students',  
  62.             component: studentsComponent  
  63.         }, {  
  64.             path: '**',  
  65.             redirectTo: 'home'  
  66.         }])  
  67.     ]  
  68. })  
  69. exportclassAppModule {}  
  70. // This is just a sample script. Paste your real code (javascript or HTML) here.  
  71.   
  72. if ('this_is' == /an_example/) {  
  73.     of_beautifier();  
  74. else {  
  75.     var a = b ? (c % d) : e[f];  
  76. }  
Step 9 Build and run the application

Build and run the application and you can see our Student page will be loaded with all Student information.

Framework

Note

First create the Database and Table in your SQL Server. You can run the SQL Script from this article to create StudentsDB database and StudentMasters Table and also don’t forget to change the Connection string from “appsettings.json".