Introduction
In this article, we are going to create a web application using ASP.NET Core 2.0 and Angular with the help of Entity Framework Core database first approach. We will be creating a sample Employee Record Management system. To read the inputs from the user, we are using Angular Forms with required field validations on the client side. We are also going to bind a dropdown list in the Angular Form to a table in the database using EF Core. We will also learn how to deploy this application on IIS.
Prerequisites
- Install .NET Core 2.0.0 or above SDK from here.
- Install the latest version of Visual Studio 2017 Community Edition from here.
- Download and install the latest version of Node.js from here.
- SQL Server 2008 or above.
We will be using Visual Studio 2017 and SQL Server 2012.
Source Code
Get the source code from Github. This repository has been updated to Angular 8 and ASP.NET Core 3.0 (preview-6).
Creating Table
- tblEmployee: – Used to store the details of employee. It contains fields such as EmployeeID, Name, City, Department, and Gender.
- tblCities: – This contains the list of cities and used to populate the City field of tblEmployee table. It contains two fields CityID and CityName.
Execute the following commands to create both tables
CREATE TABLE tblEmployee ( EmployeeID int IDENTITY(1,1) NOT NULL PRIMARY KEY, Name varchar(20) NOT NULL , City varchar(20) NOT NULL , Department varchar(20) NOT NULL , Gender varchar(6) NOT NULL ) GO CREATE TABLE tblCities ( CityID int IDENTITY(1,1) NOT NULL PRIMARY KEY, CityName varchar(20) NOT NULL ) GO
Now, we will put some data into the tblCities table. We will be using this table to bind a dropdown list in our web application from which the desired city can be selected. Use the following insert statements.
INSERT INTO tblCities VALUES('New Delhi'); INSERT INTO tblCities VALUES('Mumbai'); INSERT INTO tblCities VALUES('Hyderabad'); INSERT INTO tblCities VALUES('Chennai'); INSERT INTO tblCities VALUES('Bengaluru');
Now, our Database part has been completed. So, we will proceed to create the MVC application using Visual Studio 2017.
Create MVC Web Application
After selecting the project, a “New Project” dialog will open. Select .NET Core inside Visual C# menu from the left panel.
Then, select “ASP.NET Core Web Application” from available project types. Put the name of the project as EFNgApp and press OK.
Controllers
and Views
folders. We won’t be touching the Views folders for this tutorial since we will be using Angular 5 to handle the UI. The Controllers
folders will contain our Web API controller. The point of interest for us is the ClientApp
folder where the client side of our application resides. Inside the ClientApp/app/components
folder, we already have few components created which are provided by default with the Angular 5 template in VS 2017. These components won’t affect our application, but for the sake of this tutorial, we will delete fetchdata and counter folders from ClientApp/app/components
folder.Adding the Model to the Application
We are using Entity Framework core database first approach to create our models. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Hence run the following command:
Install-Package Microsoft.EntityFrameworkCore.Tools
After you have installed both the packages, we will scaffold our model from the database tables using the following command:
Scaffold-DbContext "Your connection string here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables tblEmployee, tblCities
Do not forget to put your own connection string (inside ” “). After this command gets executed successfully you can observe a Models folder has been created and it contains three class files myTestDBContext.cs, TblCities.cs and TblEmployee.cs. The name of your DB Context class will be the name of your database suffixed with the word Context. Here my database name is myTestDB, hence the context class name is myTestDBContext. Hence we have successfully created our Models using EF core database first approach.
Now, we will create one more class file to handle database related operations
Right click on Models folder and select Add >> Class. Name your class EmployeeDataAccessLayer.csand click Add button. At this point of time, the Models folder will have the following structure.
Open EmployeeDataAccessLayer.cs and put the following code to handle database operations.
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace EFNgApp.Models { public class EmployeeDataAccessLayer { myTestDBContext db = new myTestDBContext(); public IEnumerable<TblEmployee> GetAllEmployees() { try { return db.TblEmployee.ToList(); } catch { throw; } } //To Add new employee record public int AddEmployee(TblEmployee employee) { try { db.TblEmployee.Add(employee); db.SaveChanges(); return 1; } catch { throw; } } //To Update the records of a particluar employee public int UpdateEmployee(TblEmployee employee) { try { db.Entry(employee).State = EntityState.Modified; db.SaveChanges(); return 1; } catch { throw; } } //Get the details of a particular employee public TblEmployee GetEmployeeData(int id) { try { TblEmployee employee = db.TblEmployee.Find(id); return employee; } catch { throw; } } //To Delete the record of a particular employee public int DeleteEmployee(int id) { try { TblEmployee emp = db.TblEmployee.Find(id); db.TblEmployee.Remove(emp); db.SaveChanges(); return 1; } catch { throw; } } //To Get the list of Cities public List<TblCities> GetCities() { List<TblCities> lstCity = new List<TblCities>(); lstCity = (from CityList in db.TblCities select CityList).ToList(); return lstCity; } } }
Now, we will proceed to create our Web API Controller.
Adding the Web API Controller to the Application
Right click on Controllers folder and select Add >> New Item.
An “Add New Item” dialog box will open. Select ASP.NET from the left panel, then select “Web API Controller Class” from templates panel and put the name as EmployeeController.cs. Press OK.
This will create our Web API EmployeeController class. We will put all our business logic in this controller. We will call the methods of EmployeeDataAccessLayer to fetch data and pass on the data to the Angular frontend.
Open EmployeeController.cs file and put the following code into it.
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using EFNgApp.Models; using Microsoft.AspNetCore.Mvc; namespace EFNgApp.Controllers { public class EmployeeController : Controller { EmployeeDataAccessLayer objemployee = new EmployeeDataAccessLayer(); [HttpGet] [Route("api/Employee/Index")] public IEnumerable<TblEmployee> Index() { return objemployee.GetAllEmployees(); } [HttpPost] [Route("api/Employee/Create")] public int Create([FromBody] TblEmployee employee) { return objemployee.AddEmployee(employee); } [HttpGet] [Route("api/Employee/Details/{id}")] public TblEmployee Details(int id) { return objemployee.GetEmployeeData(id); } [HttpPut] [Route("api/Employee/Edit")] public int Edit([FromBody]TblEmployee employee) { return objemployee.UpdateEmployee(employee); } [HttpDelete] [Route("api/Employee/Delete/{id}")] public int Delete(int id) { return objemployee.DeleteEmployee(id); } [HttpGet] [Route("api/Employee/GetCityList")] public IEnumerable<TblCities> Details() { return objemployee.GetCities(); } } }
We are done with our backend logic. So, we will now proceed to code our frontend using Angular 5.
Create the Angular Service
Right click on Services folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Scripts from the left panel, then select “TypeScript File” from templates panel, and put the name as empservice.service.ts. Press OK
import { Injectable, Inject } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Router } from '@angular/router'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class EmployeeService { myAppUrl: string = ""; constructor(private _http: Http, @Inject('BASE_URL') baseUrl: string) { this.myAppUrl = baseUrl; } getCityList() { return this._http.get(this.myAppUrl + 'api/Employee/GetCityList') .map(res => res.json()) .catch(this.errorHandler); } getEmployees() { return this._http.get(this.myAppUrl + 'api/Employee/Index') .map((response: Response) => response.json()) .catch(this.errorHandler); } getEmployeeById(id: number) { return this._http.get(this.myAppUrl + "api/Employee/Details/" + id) .map((response: Response) => response.json()) .catch(this.errorHandler) } saveEmployee(employee) { return this._http.post(this.myAppUrl + 'api/Employee/Create', employee) .map((response: Response) => response.json()) .catch(this.errorHandler) } updateEmployee(employee) { return this._http.put(this.myAppUrl + 'api/Employee/Edit', employee) .map((response: Response) => response.json()) .catch(this.errorHandler); } deleteEmployee(id) { return this._http.delete(this.myAppUrl + "api/Employee/Delete/" + id) .map((response: Response) => response.json()) .catch(this.errorHandler); } errorHandler(error: Response) { console.log(error); return Observable.throw(error); } }
At this point of time, you might get an error “Parameter ’employee’ implicitly has an ‘any’ type” in empservice.service.ts file.
If you encounter this issue, then add the following line inside tsconfig.json file.
“noImplicitAny”: false
Creating Angular Components
We will be adding two components to our Angular 5 application –
- fetchemployee component – to display all the employee data and delete an existing employee data.
- addemployee component – to add a new employee data or edit an existing employee data.
import { Component, Inject } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { Router, ActivatedRoute } from '@angular/router'; import { EmployeeService } from '../../services/empservice.service' @Component({ templateUrl: './fetchemployee.component.html' }) export class FetchEmployeeComponent { public empList: EmployeeData[]; constructor(public http: Http, private _router: Router, private _employeeService: EmployeeService) { this.getEmployees(); } getEmployees() { this._employeeService.getEmployees().subscribe( data => this.empList = data ) } delete(employeeID) { var ans = confirm("Do you want to delete customer with Id: " + employeeID); if (ans) { this._employeeService.deleteEmployee(employeeID).subscribe((data) => { this.getEmployees(); }, error => console.error(error)) } } } interface EmployeeData { employeeId: number; name: string; gender: string; city: string; department: string; }
Let’s understand this code. At the very top we have imported Angular modules and EmployeeService references. After this we have @Component decorator to define the template URL for our component.
Inside the FetchEmployeeComponent class we have declared an array variable empList of type EmployeeData where EmployeeData is an interface having the properties same as our TblEmployeeModel class. Inside the getEmployees method we are calling the getEmployees method of our service EmployeeService, which will return an array of Employees to be stored in empList variable. The getEmployees method is called inside the constructor so that the employee data will be displayed as the page loads.
Next, we have delete method which accepts employeeID as parameter. This will prompt the user with a confirmation box and if the user selects yes then it will delete the employee with this employeeID.
Open fetchemployee.component.html file and put the following code into it.
<h1>Employee Data</h1> <p>This component demonstrates fetching Employee data from the server.</p> <p *ngIf="!empList"><em>Loading...</em></p> <p> <a [routerLink]="['/register-employee']">Create New</a> </p> <table class='table' *ngIf="empList"> <thead> <tr> <th>EmployeeId</th> <th>Name</th> <th>Gender</th> <th>Department</th> <th>City</th> </tr> </thead> <tbody> <tr *ngFor="let emp of empList"> <td>{{ emp.employeeId }}</td> <td>{{ emp.name }}</td> <td>{{ emp.gender }}</td> <td>{{ emp.department }}</td> <td>{{ emp.city }}</td> <td> <td> <a [routerLink]="['/employee/edit/', emp.employeeId]">Edit</a> | <a [routerLink]="" (click)="delete(emp.employeeId)">Delete</a> </td> </tr> </tbody> </table>
The code for this html file is pretty simple. On the top it has a link to create new employee record and after that it will have a table to display employee data and two links for editing and deleting each employee record.
We are finished with our fetchemployee component.
Now open addemployee.component.ts file and put the following code into it:
import { Component, OnInit } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { NgForm, FormBuilder, FormGroup, Validators, FormControl } from '@angular/forms'; import { Router, ActivatedRoute } from '@angular/router'; import { FetchEmployeeComponent } from '../fetchemployee/fetchemployee.component'; import { EmployeeService } from '../../services/empservice.service'; @Component({ templateUrl: './AddEmployee.component.html' }) export class createemployee implements OnInit { employeeForm: FormGroup; title: string = "Create"; employeeId: number; errorMessage: any; cityList: Array<any> = []; constructor(private _fb: FormBuilder, private _avRoute: ActivatedRoute, private _employeeService: EmployeeService, private _router: Router) { if (this._avRoute.snapshot.params["id"]) { this.employeeId = this._avRoute.snapshot.params["id"]; } this.employeeForm = this._fb.group({ employeeId: 0, name: ['', [Validators.required]], gender: ['', [Validators.required]], department: ['', [Validators.required]], city: ['', [Validators.required]] }) } ngOnInit() { this._employeeService.getCityList().subscribe( data => this.cityList = data ) if (this.employeeId > 0) { this.title = "Edit"; this._employeeService.getEmployeeById(this.employeeId) .subscribe(resp => this.employeeForm.setValue(resp) , error => this.errorMessage = error); } } save() { if (!this.employeeForm.valid) { return; } if (this.title == "Create") { this._employeeService.saveEmployee(this.employeeForm.value) .subscribe((data) => { this._router.navigate(['/fetch-employee']); }, error => this.errorMessage = error) } else if (this.title == "Edit") { this._employeeService.updateEmployee(this.employeeForm.value) .subscribe((data) => { this._router.navigate(['/fetch-employee']); }, error => this.errorMessage = error) } } cancel() { this._router.navigate(['/fetch-employee']); } get name() { return this.employeeForm.get('name'); } get gender() { return this.employeeForm.get('gender'); } get department() { return this.employeeForm.get('department'); } get city() { return this.employeeForm.get('city'); } }
This component will be used for both adding and editing the employee data. Since we are using a form model along with client-side validation to Add and Edit customer data we have imported classes from @angular/forms
. The code to create the form has been put inside the constructor so that the form will be displayed as the page loads.
This component will handle both Add and Edit request. So how will the system will differentiate between both requests? The answer is routing. We need to define two different route parameters, one for Add employee record and another to edit employee record, which will be defined in app.shared.module.ts
file shortly.
We have declared variable title to show on the top of page and variable id to store the employee id passed as the parameter in case of edit request. To read the employee id from the URL we will use ActivatedRoute.snapshot
inside the constructor and set the value of variable id.
ngOnInit
we are performing two operations- We are fetching the list of cities by calling getCityList method from our service. We will bind the list of cities to a dropdown list in our html page. Since we are calling getCityList method in ngOnInit, the dropdown list will be populated as the page loads.
- We will check if the id is set then we will change the title to “Edit”, get the data for that id from our service and populate the fields in our form. The value read from database will be returned as JSON and have all the properties same as we declared in our FormBuilder, hence we use setValue method to populate our form.
The save method will be called on clicking on “Save” button of our form. Based on whether it is an Add operation or an Edit operation it will call the corresponding method from our service and then upon success redirect back to fetch-employee component.
In the last one we have also defined getter functions for the control names of our form to enable client-side validation.
Open addemployee.component.html file and put the following code into it.
<h1>{{title}}</h1> <h3>Employee</h3> <hr /> <form [formGroup]="employeeForm" (ngSubmit)="save()" #formDir="ngForm" novalidate> <div class="form-group row"> <label class=" control-label col-md-12">Name</label> <div class="col-md-4"> <input class="form-control" type="text" formControlName="name" > </div> <span class="text-danger" *ngIf="name.invalid && formDir.submitted"> Name is required. </span> </div> <div class="form-group row"> <label class="control-label col-md-12" for="Gender">Gender</label> <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="gender"> <option value="">-- Select Gender --</option> <option value="Male">Male</option> <option value="Female">Female</option> </select> </div> <span class="text-danger" *ngIf="gender.invalid && formDir.submitted"> Gender is required </span> </div> <div class="form-group row"> <label class="control-label col-md-12" for="Department">Department</label> <div class="col-md-4"> <input class="form-control" type="text" formControlName="department"> </div> <span class="text-danger" *ngIf="department.invalid && formDir.submitted"> Department is required </span> </div> <div class="form-group row"> <label class="control-label col-md-12" for="City">City</label> <div class="col-md-4"> <select class="form-control" data-val="true" formControlName="city"> <option value="">--Select City--</option> <option *ngFor="let city of cityList" value={{city.cityName}}> {{city.cityName}} </option> </select> </div> <span class="text-danger" *ngIf="city.invalid && formDir.submitted"> City is required </span> </div> <div class="form-group"> <button type="submit" class="btn btn-default">Save</button> <button class="btn" (click)="cancel()">Cancel</button> </div> </form>
Here you can observe that we have attribute [formGroup]="employeeForm”
, which is our defined form group name in addemployee.component.ts
file. (ngSubmit)="save()"
will invoke our save method on form submit.
Also, every input control has attribute formControlName=”xyz”, this is used to bind FormControl to HTML. We have also defined error message for client-side validation check and it will be invoked on form submission only.
For binding the dropdown list we are using the cityList property that we have populated from the tblCities table by calling getCityList method from our service inside ngOnInit method of addemployee.component.ts file.
Defining route and navigation menu for our Application
Open /app/app.shared.module.ts file and put the following code into it.
import { NgModule } from '@angular/core'; import { EmployeeService } from './services/empservice.service' import { CommonModule } from '@angular/common'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { AppComponent } from './components/app/app.component'; import { NavMenuComponent } from './components/navmenu/navmenu.component'; import { HomeComponent } from './components/home/home.component'; import { FetchEmployeeComponent } from './components/fetchemployee/fetchemployee.component' import { createemployee } from './components/addemployee/AddEmployee.component' @NgModule({ declarations: [ AppComponent, NavMenuComponent, HomeComponent, FetchEmployeeComponent, createemployee, ], imports: [ CommonModule, HttpModule, FormsModule, ReactiveFormsModule, RouterModule.forRoot([ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'fetch-employee', component: FetchEmployeeComponent }, { path: 'register-employee', component: createemployee }, { path: 'employee/edit/:id', component: createemployee }, { path: '**', redirectTo: 'home' } ]) ], providers: [EmployeeService] }) export class AppModuleShared { }
Here we have also imported all our components and defined the route for our application as below
- home – which will redirect to home component
- fetch-employee – to display all employee data using fetchemployee component
- register-employee – to add new employee record using createemployee component
- employee/edit/:id – to edit existing employee record using createemployee component
/app/components/navmenu/navmenu.component.html
file and put the following code to it<div class='main-nav'> <div class='navbar navbar-inverse'> <div class='navbar-header'> <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' [routerLink]="['/home']">ASPCoreWithAngular</a> </div> <div class='clearfix'></div> <div class='navbar-collapse collapse'> <ul class='nav navbar-nav'> <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/home']"> <span class='glyphicon glyphicon-home'></span> Home </a> </li> <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/fetch-employee']"> <span class='glyphicon glyphicon-th-list'></span> Fetch employee </a> </li> </ul> </div> </div> </div>
And that’s it. We have created our first ASP.NET Core application using Angular 5 and Entity Framework core database first approach.
Execution Demo
Press F5 to launch the application.
A web page will open as shown in the image below. Notice the URL showing route for our home component. And navigation menu on the left showing navigation link for Home and Fetch Employee pages.
Click on Fetch Employee in the navigation menu. It will redirect to fetch employee component and displays all the employee data on the page.
Since we have not added any data, hence it is empty.
Click on CreateNew to navigate to /register-employee
page. Add a new Employee record as shown in the image below. You can observe that the City field is a dropdown list, containing all the city names that we have inserted into tblCities table.
If we miss the data in any field while creating employee record, we will get a required field validation error message
After inserting the data in all the fields, click on “Save” button. The new employee record will be created and you will be redirected to the /fetch-employee page, displaying records of all the employees. Here, we can also see action methods Edit and Delete.
If we want to edit an existing employee record, then click Edit action link. It will open Edit page as below where we can change the employee data. Notice that we have passed employee id in URL parameter.
Here we have changed the City of employee Rahul from Hyderabad to Chennai. Click on “Save” to return to the fetch-employee page to see the updated changes as highlighted in the image below:
If we miss any fields while editing employee records, then Edit view will also throw required field validation error message as shown in the image below:
Now, we will perform Delete operation on an employee named Swati having Employee ID 2. Click on Delete action link which will open a JavaScript confirmation box asking for a confirmation to delete.
Once we click on Delete button the employee with name Swati will be removed from our record and you can see the updated list of employee as shown below.
Deploying the Angular 5 application
Open tsconfig.json file and add the following line
“strictNullChecks”: false
Refer to the image below:
When we publish the application , Visual Studio will run “node node_modules/webpack/bin/webpack.js –config webpack.config.vendor.js –env.prod” command. Adding the above mentioned line in tsconfig.json
file will ensure that this command will not strictly check for any null values in our application.
Please note that if you are not publishing this application then you do not need to add “strictNullChecks”: false in your tsconfig.json file.
After this follow the same steps mentioned at Deploying a Blazor Application on IIS
Conclusion
We have successfully created an ASP.NET Core application using Angular 5 and Entity Framework core database first approach with the help of Visual Studio 2017 and SQL Server 2012. We have used Angular forms to get data from the user and also bind the dropdown list to database table using Entity framework.
You can also find this article at C# Corner.
Preparing for interviews !!! Read my article on C# Coding Questions For Technical Interviews
You can check my other articles on ASP .NET Core here
See Also
- CRUD Operations With ASP.NET Core Using Angular 5 and ADO.NET
- Getting Started With Angular 5 Using Visual Studio Code
- CRUD Operation With ASP.NET Core MVC Using Visual Studio Code and EF
- CRUD Operation With ASP.NET Core MVC Using ADO.NET and Visual Studio 2017
- CRUD Operation With ASP.NET Core MVC using Visual Studio Code and ADO.NET
- ASP.NET Core – Getting Started With Blazor
Hi..
You Have Any Searching Operation Code on Gridview then send me the code.
Thanks for reading my article.
A simple google search can answer your question. Meanwhile you can chek the below links
https://www.aspsnippets.com/Articles/Search-records-in-GridView-and-highlight-results-in-ASPNet-using-C-and-VBNet.aspx
https://www.codeproject.com/Tips/876630/Searchable-Gridview-using-Jquery-Easiest-Way
https://www.c-sharpcorner.com/UploadFile/85ed7a/searching-records-from-database-and-display-in-gridview-and/
Hi Ankit..this project doesn’t work on my system..it gives me cannot get error.
What to do plz tell..
Get the source code from GitHub and try to run it. The code is correct and working fine. If you are still facing the issue, open a question on StackOVerflow. If someone has faced a similar issue, they will help you.
Thank you for send me the link
but i need the serching functionality in this code in angular with asp.net.
Thank you very much. I was searching for this kind of approach only on internet but finally your article make my work. You saved my lot of time. I want to connect with you can you please give me your whats up no.
Thanks again
God Bless You
Thanks for reading my article. Please contact me over Facebook. Profile – https://www.facebook.com/ankit.sharma.3726613
Hi,
Can you write an article in which the user has to login into his account and after login we will maintain his session and also implement (Login,Logout functionality).
Please tell me the approach for this.
Thanks
Thanks for reading my article. i will certainly try writing on session management.
Thanks
Hi,
I am getting the error
Scaffold-DbContext “Your connection string here” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables tblEmployee, tblCities
Build failed
Please help me.
put the correct connection string inside “” and try running the app
Please check your npm all js file is loaded , I think , you can see some file warning symbol . Please restore all js file.
And Rebuild the project.
Are you sure you put your connection string within the quotes?
When i try to fetch Employees, i’m getting “Loading ” message and data is not loading. What could be the issue? I’m not receiving any error.
Please make sure that your web api is returning correct data. to check the error console tab in developer’s tool.
It was a routing issue. when i removed “[Route(“api/[controller]”)]” from EmployeeController.cs it worked. This was auto generated by visual studio.
Thanx for your response.
Glad that your issue is resolved. Cheers !!!
thanks, for me also was same issue, when i removed “[Route(“api/[controller]”)]” from EmployeeController.cs, now working fine.
Great !!!
Hi, i got this error.
An error occurred while starting the application.
AggregateException: One or more errors occurred. (Cannot find module ‘./wwwroot/dist/vendor-manifest.json’
There is no such file in the folder.
Thanks.
Please refer to this link https://github.com/aspnet/JavaScriptServices/issues/780
Thank you very much
Hi,
I can not able to call controller for post method but i can able to call controller for get method, using your code in my project. So please help me out.
saveEmployee(employee) {
debugger;
return this._http.post(this.myAppUrl + ‘api/Employee/Create’, employee)
.map((response: Response) => response.json())
.catch(this.errorHandler)
}
getEmployees() {
debugger;
return this._http.get(this.myAppUrl + ‘api/Employee/Index’)
.map((response: Response) => response.json())
.catch(this.errorHandler);
}
thanks,
when i removed “[Route(“api/[controller]”)]” from EmployeeController.cs, now working fine
I’m not getting the cityList dropdown list. can you let me how to test/debug your api/Employee/GetCityList
You can put a breakpoint in the data access layer to debug. Please verify if your connection string is correct. Also check if your table contains the data or not.
How to get connection string and from where
You need to provide connection string for your DB connection. You can search on the internet for the process of getting the connection string for your database. I cannot explain it here as it is beyond the scope of this article.
Unexpected token < in JSON at position 0
at JSON.parse ()
I’m facing this error in the console while fetching the data.
The reason is that the server is returning data in HTML/XML format but angular is expecting in json format.
How to resolve it?
It’s amazing… Exactly what I was looking for!
Thanks for reading my article. I am glad this solves your issues.
Hi
I got some cors issue in Angular .so kindly please help.
Hi,
I dont have the folder structure i have a src folder and no component folder do you know why ?
Thanks,
The folder structure in latest version of Angular is changed. However, this will not affect the coding/logic of the application described here. You can create your components in src/app folder of current version of Angular (~7.0).
Hi,
I’m getting following error on creating new employee.
Cannot GET /api/Employee/GetCityList
I check my connection string, it working perfectly. I manually insert a record of employee, which is showing on fetch-employee screen. but when I click on create new, I got the following error
Cannot GET /api/Employee/GetCityList.
please advice its solution ASAP.
Thanks & Best Regards
Hi, Thanks for reading my article. Have you checked you API endpoint? If not plz verify it using postman. Also check if other API are working correctly. If the issue still persists then match your code with my code sample mentioned in this article.
hi,
thanks for the reply.
Actually, the issue is with routing. when I use “action” in [HttpGet(“[action]”)], it get the city list. now the angularjs cannot get the following link due to id in last. even I use [HttpGet(“[action]”)],
cannot get api/Employee/Details/2
Please advice any proper solution for it.
thanks & best regards
As i mentioned in my previous comment, plz match your code with my code and find out the difference. It will resolve your issue.
Hy,
I get to know how to create sample Employee Record Management system.We are In the introduction it is said we have to use u Angular Forms with required field validations on the client side. a dropdown list in the Angular Form to a table in the database using EF Core. i also learn how to deploy this application on IIS. This blog show step by step process how to create record management system. Thanks for sharing this blog.
Great topic but having some issue while executing following codes for Scafolding or CRUD
Scaffold-DbContext “Server=abc-pc;Database=Northwind;Trusted_Connection=True;” Microsoft.EntityFrameworkCore.SqlServer-OutputDir Models -Tables tblEmployee, tblCities
what kind of error are you getting? Please verify your connection string.
I am using like this
Scaffold-DbContext “Data Source=PCNAME;Initial Catalog=Book;Integrated Security=False;User ID=PC1;pwd=PC2” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Categories, UserType, UserMaster, Book, Cart, CartItems, CustomerOrders, CustomerOrderDetails, Wishlist, WishlistItems -force
Error
To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration – see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 – No process is on the other end of the pipe.)
—> System.ComponentModel.Win32Exception (233): No process is on the other end of the pipe.
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
Thanks for sharing this! I’m curious, why do you have the Add, Updated, and Delete functions in DataAccessLayer return an integer 1? I’m new to C#, and I’m trying to understand the way things work.
I need to notify the controller on success of my operations, so i am returning an integer on success. In case of failure it will throw an error. This is one way of implementation. You can use any other way also to return on success.
Nice tutorial, how to run this on local IIS without publishing?
Since this is an ASP.NET Core hosted app, hence the process will be similar to any other ASP.NET Core app. Please follow the steps mentioned at https://ankitsharmablogs.com/deploying-a-blazor-application-on-iis/
you don’t cover where @Inject(‘BASE_URL’) came from.
especially the ‘BASE_URL’ bit
Great Article. where can I download the source code for this?
Thank you
Please get the source code from the GitHub link mentioned in the article.
I am new to Angular… This is very helpful and useful information for me. It is very good example of CRUD and it is very simple.
I would like to see some more enhancements to the project such as adding new table for State abbreviation and state full name and rowId. Employee table should have state rowId which is the foreign key of the State table.
I have done it a different way and I have errors 404 on the client side since I have used .include(tblState) in the Entity of Employee.
Another enhancement is a popup like windows to update Employer and superviser’s information. I believe that this feature will be useful for a rookie like me (of course another table will be needed tblEmployer which contains supervisor, department etc…)
Thank you for sharing this information.
I am following your instructions and have built the project. I am gettingthe message BadImageFormatException: Invalid number of sections in declared in PE header.
Can you advise?
it’s Very good article brother nicely explained..
This is a very good article; however, your GitHub code is quite different. Any chance you would update some of the major points in this article? For example, the imports are different in Angular 8 & the npm packages are different. Thanks in advance!
Updating article with each Angular update is not possible. I would suggest you to refer to the Code on GitHub for all the latest changes. The core concept is same only few imports will defer.
Hello Ankit
Great tutorial !
Running into some concurrency issues . How do you resolve following error:
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: ‘Database operation expected to affect 1 row(s) but actually affected 0 row(s).
Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962 for information on understanding
and handling optimistic concurrency exceptions.’
Thank You.
I am not facing any issues with the code. Please get the source code from GitHub and debug to see the exact issue.
Hello ANKIT
This is an awesome article explaining CRUD operations in details. However I am having some issues when updating a record I get the following error message :
Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException: ‘Database operation expected to affect 1 row(s) but actually affected 0 row(s). Data may have been modified or deleted since entities were loaded. See http://go.microsoft.com/fwlink/?LinkId=527962
for information on understanding and handling optimistic concurrency exceptions.’
This exception was originally thrown at this call stack:
[External Code] in EmployeeDataAccessLayer.cs
public Employee GetEmployeeData(int id)
{
try
{
Employee employee = db.Employee.Find(id);
return employee;
}
catch
{
throw;
}
}
[External Code] in EmployeeController.cs
I would really appreciate if you help resolve this issue.
Thank You !
I am not facing any issues with the code. Please get the source code from GitHub and debug to see the exact issue.
Hi bro,
I want to change some thing on your code .
But now I don’t know how to do it.
Can you help me ?
I have sent an invitation to your facebook . hope you will to apcept for me. and then I want to ask you about code.
Thanks for your article
It is not possible for me to work on your personal requirements. Please refer to stack overflow for any personal questions.
Severity Code Description Project File Line Suppression State
Error The feed ‘nuget.org [https://api.nuget.org/v3/index.json]’ lists package ‘Microsoft.Identity.Client.3.0.8’ but multiple attempts to download the nupkg have failed. The feed is either invalid or required packages were removed while the current operation was in progress. Verify the package exists on the feed and try again.
Unable to find package ‘Microsoft.Identity.Client.3.0.8’.
This is super helpful since I’m just starting Angular! I’ve been so confused with CRUD topic even when I started with React but now I’m finally learning because of this. Thanks for sharing this.
you are really a great man for sharing the resources. God Bless you
After reading 5 or 6 articles all to the same extend … you propose EntityFrameworkCore – but how come you don’t and I can’t create/add a real edmx model? going back to the old “using x = mydatabase connection” seems a step in the wrong direction
Hi Ankit
I am using like this
Scaffold-DbContext “Data Source=PCNAME;Initial Catalog=Book;Integrated Security=False;User ID=PC1;pwd=PC2” Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables Categories, UserType, UserMaster, Book, Cart, CartItems, CustomerOrders, CustomerOrderDetails, Wishlist, WishlistItems -force
Error
To protect potentially sensitive information in your connection string, you should move it out of source code. You can avoid scaffolding the connection string by using the Name= syntax to read it from configuration – see https://go.microsoft.com/fwlink/?linkid=2131148. For more guidance on storing connection strings, see http://go.microsoft.com/fwlink/?LinkId=723263.
Microsoft.Data.SqlClient.SqlException (0x80131904): A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 – No process is on the other end of the pipe.)
—> System.ComponentModel.Win32Exception (233): No process is on the other end of the pipe.
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
This seems to be an issue with your database. Please verify your connections string. The code is working correctly.
Hi
Ankit
Connection string working fine no issue
Hi
Ankit
Some issue have in this code
Method not found: ‘System.Nullable`1 Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationalValueGenerationConvention.GetValueGenerated
Hi
Ankit
Working Fine Connection string basically Registration not working and login not working
when I run application Cart not working
This is the error
System.MissingMethodException: ‘Method not found: ‘System.Nullable`1 Microsoft.EntityFrameworkCore.Metadata.Conventions.RelationalValueGenerationConvention.GetValueGenerated(Microsoft.EntityFrameworkCore.Metadata.IProperty, System.String, System.String)’.’
can you resolve your issues
https://github.com/AnkitSharma-007/BookCart/issues/10