Click here to Skip to main content
14,145,240 members
Click here to Skip to main content
Add your own
alternative version

Stats

23.3K views
732 downloads
31 bookmarked
Posted 19 Dec 2016
Licenced CPOL

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

, 25 Dec 2016
Rate this:
Please Sign up or sign in to vote.
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.

Introduction

Now, it has become easier to create an Angular2 application in ASP.NET Core using the ASP.NET Core Template Pack. ASP.NET Core Template contains the following collection of .NET Core Project Templates.

  • ASP.NET Core Angular 2 Starter Application (.NET Core)
  • ASP.NET Core MVC Starter Application (.NET Core)
  • Static Website (.NET Core)
  • Vue.js with Webpack (.NET Core)

After installing our ASP.NET Core Template pack, we can see that the new templates have been added to our Visual Studio.

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. (Reference link).

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.

Make sure, you have installed all the prerequisites in your computer. If not, then download and install all, 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 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).

Make sure that you have installed all the listed tools before starting your ASP.NET Core Template Pack.

Now, it’s time to install ASP.NET Core Template pack. There are two methods for installing the ASP.NET Core Template Pack.

First method to install ASP.NET Core Template Pack

Download ASP.NET Core Template Pack visz file from this link.

Second Method to install ASP.NET Core Template Pack

Open Visual Studio 2015 >> Tools >> Select Extensions and Updates.

In the right side click on Search, enter “ASP.NET Core Template Pack” and download the template.

Install the ASP.NET Core Template Pack.

After installation, restart the Visual Studio 2015. Now, we can see that ASP.NET Core Template Pack has been added under web project templates.

Using the code

Now, let’s see how to create our first ASP.NET Core Angular 2 application.

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.

USEMASTER  
GO  
--1) Check  
for the Database Exists.If the database is exist then drop and create new DB  
IFEXISTS(SELECT[name] FROMsys.databasesWHERE[name] = 'StudentsDB')  
DROPDATABASEStudentsDB  
GO  
CREATEDATABASEStudentsDB  
GO  
USEStudentsDB  
GO  
--1) //////////// StudentMasters  
IFEXISTS(SELECT[name] FROMsys.tablesWHERE[name] = 'StudentMasters')  
DROPTABLEStudentMasters  
GO  
CREATETABLE[dbo].[StudentMasters](  
        [StdID] INTIDENTITYPRIMARYKEY, [StdName][varchar](100) NOTNULL, [Email][varchar](100) NOTNULL, [Phone][varchar](20) NOTNULL, [Address][varchar](200) NOTNULL  
    )  
    --insert sample data to Student Master table  
INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
VALUES('Shanu', 'syedshanumcain@gmail.com', '01030550007', 'Madurai,India')  
INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
VALUES('Afraz', 'Afraz@afrazmail.com', '01030550006', 'Madurai,India')  
INSERTINTO[StudentMasters]([StdName], [Email], [Phone], [Address])  
VALUES('Afreen', 'Afreen@afreenmail.com', '01030550005', 'Madurai,India')  
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.

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

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

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.

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. 

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.

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

View Folder
This is our MVC View folder.

Other Important filesWe 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
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. 

"Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",  
"Microsoft.EntityFrameworkCore.Tools": "1.0.0-preview2-final" 

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

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

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.

In this appsettings.json file add our connection string 

"ConnectionStrings": {  
    "DefaultConnection": "Server=YOURDBSERVER;Database=StudentsDB;user id=SQLID;password=SQLPWD;Trusted_Connection=True;MultipleActiveResultSets=true;"  
},  

Note 
Change the SQL connection string as per your local connection.

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

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.

Now in this class we first create property variable, and add student. We will be using this in our WEB API controller. 

using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Threading.Tasks;  
usingSystem.ComponentModel.DataAnnotations;  
namespace Angular2ASPCORE.Data {  
    publicclassStudentMasters {  
        [Key]  
        publicintStdID {  
            get;  
            set;  
        }  
        [Required]  
        [Display(Name = "Name")]  
        publicstringStdName {  
            get;  
            set;  
        }  
        [Required]  
        [Display(Name = "Email")]  
        publicstring Email {  
            get;  
            set;  
        }  
        [Required]  
        [Display(Name = "Phone")]  
        publicstring Phone {  
            get;  
            set;  
        }  
        publicstring Address {  
            get;  
            set;  
        }  
    }  
}  

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.

In this class we inherit DbContext and created Dbset for our students table.

using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Threading.Tasks;  
usingMicrosoft.EntityFrameworkCore;  
  
namespace Angular2ASPCORE.Data {  
    publicclassstudentContext: DbContext {  
        publicstudentContext(DbContextOptions < studentContext > options): base(options) {}  
        publicstudentContext() {}  
        publicDbSet < StudentMasters > StudentMasters {  
            get;  
            set;  
        }  
    }  
}  

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.

services.AddDbContext < studentContext > (options =>  
    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.

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

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.

using System;  
usingSystem.Collections.Generic;  
usingSystem.Linq;  
usingSystem.Threading.Tasks;  
usingMicrosoft.AspNetCore.Mvc;  
using Angular2ASPCORE.Data;  
usingMicrosoft.EntityFrameworkCore;  
usingMicrosoft.AspNetCore.Http;  
// For more information on enabling Web API for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860  
  
namespace Angular2ASPCORE.Controllers {  
    [Produces("application/json")]  
    [Route("api/StudentMastersAPI")]  
    publicclassStudentMastersAPI: Controller {  
        privatereadonlystudentContext _context;  
  
        publicStudentMastersAPI(studentContext context) {  
            _context = context;  
        }  
  
        // GET: api/values  
  
        [HttpGet]  
        [Route("Student")]  
        publicIEnumerable < StudentMasters > GetStudentMasters() {  
            return _context.StudentMasters;  
  
        }   
    }  
}  

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.

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.

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.

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. 

import {  
    Component  
} from '@angular/core';  
import {  
    Http  
} from "@angular/http";  
@Component({  
    selector: 'students',  
    template: require('./students.component.html')  
})  
  
exportclassstudentsComponent {  
    public student: StudentMasters[] = [];  
    myName: string;  
    constructor(http: Http) {  
        this.myName = "Shanu";  
        http.get('/api/StudentMastersAPI/Student').subscribe(result => {  
            this.student = result.json();  
        });  
    }  
}  
exportinterfaceStudentMasters {  
    stdID: number;  
    stdName: string;  
    email: string;  
    phone: string;  
    address: string;  
}  

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.

Write the below html code to bind the result in our html page

<h1>Angular 2 with ASP.NET Core Template Pack, WEB API and EF 1.0.1  </h1>
<hr />
<h2>My Name is : {{myName}}</h2>
<hr />
<h1>Students Details :</h1> 
<p *ngIf="!student"><em>Loading Student Details please Wait ! ...</em></p>
<table class='table' style="background-color:#FFFFFF; border:2px #6D7B8D; padding:5px;width:99%;table-layout:fixed;" cellpadding="2" cellspacing="2" *ngIf="student">
    <tr style="height: 30px; background-color:#336699 ; color:#FFFFFF ;border: solid 1px #659EC7;">
        <td width="100" align="center">Student ID</td>
        <td width="240" align="center">Student Name</td>
        <td width="240" align="center">Email</td>
        <td width="120" align="center">Phone</td>
        <td width="340" align="center">Address</td>
    </tr>
    <tbody *ngFor="let StudentMasters  of student">
        <tr>
            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                <span style="color:#9F000F">{{StudentMasters.stdID}}</span>
            </td>
            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                <span style="color:#9F000F">{{StudentMasters.stdName}}</span>
            </td>
            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                <span style="color:#9F000F">{{StudentMasters.email}}</span>
            </td>
            <td align="center" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                <span style="color:#9F000F">{{StudentMasters.phone}}</span>
            </td>
            <td align="left" style="border: solid 1px #659EC7; padding: 5px;table-layout:fixed;">
                <span style="color:#9F000F">{{StudentMasters.address}}</span>
            </td>
        </tr>
    </tbody>
</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.

<li[routerLinkActive]="['link-active']">  
    <a[routerLink]="['/students']">  
        <spanclass='glyphiconglyphicon-th-list'>  
            </span> Students  
     </a>  
</li> 

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

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { UniversalModule } from 'angular2-universal';
import { AppComponent } from './components/app/app.component'
import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';
import { FetchDataComponent } from './components/fetchdata/fetchdata.component';
import { CounterComponent } from './components/counter/counter.component';
import { studentsComponent } from './components/students/students.component';

@NgModule({
    bootstrap: [ AppComponent ],
    declarations: [
        AppComponent,
        NavMenuComponent,
        CounterComponent,
        FetchDataComponent,
        HomeComponent,
        studentsComponent
    ],
    imports: [
        UniversalModule, // Must be first import. This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: 'home', component: HomeComponent },
            { path: 'counter', component: CounterComponent },
            { path: 'fetch-data', component: FetchDataComponent },
            { path: 'students', component: studentsComponent }, 
            { path: '**', redirectTo: 'home' }
        ])
    ]
})
export class AppModule {
}

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.

Points of Interest

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".

History

Angular2ASPCORE.zip - 2016/12/20

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

syed shanu
Team Leader
India India
Microsoft MVP | Code Project MVP | CSharp Corner MVP | Author | Blogger and always happy to Share what he knows to others. MyBlog

My Interview on Microsoft TechNet Wiki Ninja Link

You may also be interested in...

Pro

Comments and Discussions

 
GeneralMy vote of 5 Pin
Mahsa Hassankashi26-Nov-17 0:00
memberMahsa Hassankashi26-Nov-17 0:00 
Questionhow to modify the template to get angular 4 to work Pin
Member 1055098829-Mar-17 8:37
memberMember 1055098829-Mar-17 8:37 
Questionnpm - not installed error Pin
Eagle329-Feb-17 9:16
memberEagle329-Feb-17 9:16 
GeneralMy vote of 5 Pin
Sampath Lokuge29-Dec-16 20:28
memberSampath Lokuge29-Dec-16 20:28 
QuestionAdd Microsoft.EntityFrameworkCore 1.0.1 to project.json file Pin
Member 1035553623-Dec-16 8:37
memberMember 1035553623-Dec-16 8:37 
QuestionError Pin
Jon Alberghini23-Dec-16 1:45
memberJon Alberghini23-Dec-16 1:45 
QuestionYeah!! Pin
Touristas21-Dec-16 19:53
memberTouristas21-Dec-16 19:53 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01 | 2.8.190518.1 | Last Updated 25 Dec 2016
Article Copyright 2016 by syed shanu
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid