CRUDing with AngularJS 1.7.x, ASP.NET WebAPI2 and Entity Framework Tutorial — Part 1 (of 2)
So if you are like me and just started out with AngularJS (yes new versions are out now but baby steps please…) and WebAPI2 to feed your AngularJS something useful, then stay tuned. We will be covering the creation of a basic AngularJS application and its integration with a WebAPI2 back-end, the focus being on the CRUD aspect between the two, as well as consuming scaffolded controllers without too much redevelopment.
This tutorial will be split into two parts, the first being the creation of the WebAPI2 back-end, and the second being the AngularJS front-end. To jump to the second part, please click here.
This tutorial is adapted from Shamim Uddin’s. Shout out to him for placing for the ground work for us.
- Have a basic knowledge of MVC and/or WebAPI(2). I have worked with MVC before and was a small jump to WebAPI
- Visual Studio, preferably 2017
- SQL Server installed locally (any edition will do really) and SSMS (SQL Server Management Studio — cause who likes working in consoles?)
Its easier for me to work with a stand alone instance of SQL, but you are welcome to use whatever other method tickles your fancy.
Why Are We Using These Technologies?
It seems that the development space has shifted focus to a better UI experience for the end user. This is better achieved with SPAs (Single Page Applications) as all the core content like CSS and scripts are loaded only once and in the beginning, making subsequent usage very quick and seamless.
In today’s world, AngularJS (and the later Angular) is the framework used to reach the goal of an SPA site. There are other benefits especially with the later version, however let’s keep it simple and discuss that another time.
The AngularJS framework doesn’t provide us with a back-end so we will be using it in conjunction with ASP.NET WebAPI2.
WebAPI2 is .NET’s way of exposing your data and services, which AngularJS can consume through HTTP. I am more familiar with .NET so naturally went with this but don’t feel limited to only using WebAPI2 with AngularJS.
Setting up the Back-End
We will be using ASP.NET WebAPI2 to create the back-end, with Entity Framework doing the integration with the DB.
.NET works well with SQL Server, so we will start off with creating a new database directly on your local instance. Start up SSMS and run the below script:
IF EXISTS(SELECT * FROM SYS.DATABASES WHERE NAME='UNIVERSITY_TEST')
DROP DATABASE UNIVERSITY_TEST;CREATE DATABASE UNIVERSITY_TEST;USE UNIVERSITY_TEST;DROP TABLE IF EXISTS STUDENTS;
DROP TABLE IF EXISTS SUBJECTS;
DROP TABLE IF EXISTS SUBJECT_REGISTRATIONS;CREATE TABLE STUDENTS (
ID INT IDENTITY(1,1) PRIMARY KEY,
FIRST_NAME VARCHAR(50) NOT NULL,
LAST_NAME VARCHAR(50) NOT NULL,
)CREATE TABLE SUBJECTS (
ID INT IDENTITY(1,1) PRIMARY KEY,
CODE VARCHAR(6) NOT NULL,
DESCRIPTION VARCHAR(250) NOT NULL
)CREATE TABLE SUBJECT_REGISTRATIONS (
ID INT IDENTITY(1,1),
STUDENT_ID INT NOT NULL REFERENCES STUDENTS(ID) ON DELETE CASCADE ON UPDATE CASCADE,
SUBJECT_ID INT NOT NULL REFERENCES SUBJECTS(ID) ON DELETE CASCADE ON UPDATE CASCADE
)INSERT INTO STUDENTS (FIRST_NAME, LAST_NAME) VALUES
('SHWANTA','BURGHART');INSERT INTO SUBJECTS (CODE,DESCRIPTION) VALUES
('COS110','PROGRAM DESIGN: INTRODUCTION'),
('INL120','INFORMATION SCIENCE: ORGANISATION AND REPRESENTATION OF INFORMATION'),
('JCP202','COMMUNITY-BASED PROJECT');INSERT INTO SUBJECT_REGISTRATIONS (STUDENT_ID,SUBJECT_ID) VALUES
Cool, so now we have our own database, with some tables and random data for easy development and testing.
Let’s move into Visual Studio and create a new Web Application Project. Let’s keep it simple and stay away from
Add an Entity Data Model (EDM) to your Model’s folder named
We will use the ‘Code First from database’ option. Configure the connection to the DB (save it to the config file) and add all the tables, skipping the pluralisation of the object names. This should create the below objects in your Models folder:
You will need to build your project first before the controller scaffolding will be successful. Build your project now.
I don’t pass up the opportunity to make life easy so let’s make use of Visual Studio’s option to scaffold the controllers. This will generate consumable CRUD methods (APIs) for us to consume via AngularJS.
You can leave out async controller actions as they don’t help us out in this small project, but you can read up on them here.
You should now have your first controller. You can repeat the above process for the
Subject models and their controllers, however we will not be making use of them for the rest of the tutorial. These will be for you to complete on your own.
Go take some time to have a look at the generated code. It looks quite similar to the MVC generated controllers if you have played with them before…
The back-end is now ready for consumption. You can start it up, taking note of the port number. View the API section of the site:
Select the first API and scroll down to the ‘Response/Formats’ section. You should see an error about a
Self referencing loop detected. Oops!
Let’s assume you don’t know what’s supposed to be in that block and ignore the error message. Let’s move onto testing the WebAPI with Curl.
Testing the API with Curl
Before we jump to our AngularJS project, let’s test and play around with our APIs that we just created, to make sure they working. We can use a tool called Curl to simulate HTTP calls. You can install Curl from here if you don’t already have it.
If you are unfamiliar with Curl and how to use it, you can read up on it here.
We are going to try and return a list of students from our API, which means we are going to run the below command:
curl --header “Accept:application/json” http://localhost:63718/api/student/
If you are coming form an MVC background and are not sure why there is a ‘…/api/…’ in the path, then I suggest giving this a read. Basically is the default exposure/routing for WebAPI and its (API)controllers.
The above Curl command will interact with the below API from our running ASP.NET WebAPI2 project.
This API resolved to the below code:
Understand the connections and flow.
Let’s run the Curl command now. You should receive a massive error message like the below:
A side note here, you may have noticed that one of the highlighted error messages is similar to the one we received from the ‘Response Formats’ section of the APIs that we deployed. We will come back to this later.
Even though we scaffolded everything, we still have issues! But fear not, for we have a solution!
Alright let’s open this can… In our database (and consequently or models),
students has a one-to-many relationship with ‘student_registrations’. In the Student Model this is reflected through the
ICollection field at the bottom:
And to complete the self reference…
These structures are used by Entity Framework to express the database foreign key relationships. It is with these objects that the serialiser is struggling. It is probably best to leave them where they are as we have scaffolded these objects. We will have to find a work around…
Depending on what part of the error message you Googled first, you may have been directed here first, but this doesn’t really explain too much. With a refined error message search, you may have been directed here and finally here, which has the solution and explanation we are looking for.
Add the below code to your WebApiConfig.cs file which can be found under the App_Start folder. This will change the behavior of the serialiser by forcing it to ignore self reference loops.
config.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
Let’s run our WebAPI2 project again and have a look at the ‘Response Formats’ on the Get Students API. You should see a Json formatted string with sample data, showing the structure that we can expect from the response data.
If you scroll down a bit further and you will find that there is still an issue with the ‘application/xml’ and ‘text/xml’… F**k that. Json is working… that’s good enough for me. Next!
Now that the ‘application/json, text/json’ section is populating, we can tell that is gives us an example of the data that will be returned as well as its structure. We will be using this in the second part of this tutorial.
Rerun the Curl command again and you should get the expected data.
Our WebAPI is now running and we have tested that it works. Let’s move onto the AngularJS section which is covered in Part 2 of this tutorial.