Introduction to AngularJS for .NET Developers

What is AngularJS?

AngularJS is a Javascript-based open-source framework primarily developed by Google used to address challenges such as

  • Separation of Concerns
  • Maintainability: Much like any other framework, Angular allows you to group your codes in a way that makes sense to you. You can group objects based on logical grouping and even the Object type as long as you are consistent throughout.
  • Testability: Because you can separate the Controller without any dependency from the HTML objects, you can more easily isolate the logic. Angular was also developed with Unit Testing in mind.
  • Ease of Development: AngularJS allows you to pass some of the common, yet hard work to it. For instance, instead of  making a method calling a WebAPI yourself using, say, AJAX: you can pass the URL to what is called a Service.
  • Data Binding

As well as challenges in development of Single Page Applications (SPAs). SPAs will not be covered in this post, but I hope that after reading this, it will be easier for you to do your research.

Why use a Javascript Framework?

Much like a Server-Side code, you want to have clean, maintainable and testable codes. Most .NET developers are guilty of having clean Server-Side codes while thinking that the scripts are “purely” UI: And in doing so thinking that as long as the scripts work, it’s all part of the View layer.

Times have changed, though. In the modern web where Javascript has been a first-class citizen, having your logic and DOM manipulation is unacceptable. In some applications even, you will find that you’ll have more client-side scripts than Server-Side, and with a good volume of Javascript running around your project, keeping it testable and maintainable should be a priority.

Your First AngularJS Project

Codes discussed here can be found in

As implied in the title, we are dealing with a .NET MVC project with a AngularJS Javascript Framework but then it would basically be a WebAPI in the backend and everything else is happening in Javascript. Here are some things to take notice of:

  • We do all application logic in the client: Including routing. Now comes the question of security: How secure is an Angular application? It all comes down to how much logic do we want to keep on the client and how much do we want to keep on the server? Also, minifying is a method of “encryption”

Integrating to your Application

Let’s enumerate the elements that I was able to integrate to my application, define each of them and see how I implemented them. The purpose of this blog is to introduce the concepts while the purpose of the sample codes is to show how they all come together


Controllers are Javascript objects created that take care of the base logic. It is also the one that builds your models. Notice this piece:

var PatientController = function ($scope, $http) {
= “Patients”;

It shows us

  • The Patient Controller, a function that contains the logic
  • That you can create objects from inside the controller. In this case, we are adding a Header property inside the model that will be returned to the View. We used a string here in this example, but in reality we can use nested objects.


Views are your Presentation Layers which is basically your HTML. It includes the

  • Binding Expressions: Binding expressions are expressions that you put inside double-curly braces used to populate the View as it gets manipulated by the Controller. You don’t do much assignments in Angular because it does the bindings for you. For instance, say you have this expression in your View:

    . The value of this div will get changed automatically when you update this same model in the controller like so: = “John Conrad”

  • Directives: Directives are signified as HTML attributes that start with a ng- which is shorthand for Angular. The very first thing that you will probably learn when trying to code Angular is ng-app which is a directive! We’ll define this further later


Models are the objects that bind together the Business Logic (Controllers) with the Presentation (View). Models are generated on the fly by the Controller.


Directives are extended HTML attributes with the ng- prefix. Directives generally tells you that, hey, Angular cares about this part of the UI. For instance, we start our application with the ng-app directive to say that the whole section surrounded by the ng-app tag is a controlled section by Angular.

ng-model on the other hand is a directive that you add in to form controls, like inputs telling Angular that the said control is bound to a model.


An Angular Service is a shared function or object in Angular. That’s a vague definition because services do come in a variety of flavours. Some of them can be called like a function, and some of them look like an object where you invoke a part of it to work. Angular provides built-in Services signified by a $ sign at the beginning. On top of that,

  • Services called like a function
  • Services where you invoke a part of it to work

In this same piece, you’ll notice that I used 2 Services:

var PatientController = function ($scope, $http) {
= “Patients”;
  • The Scope Service which allows me to communicate with the View
  • The Http Service which allows me to call a Restful URL

To call built-in Angular Services, all you need to do is to add them in as a parameter. Look at the code above: we need the http object, and so we add a $http as a parameter. We don’t need to supply values to this: Angular will do that for us.

If you want, perhaps, a countdown timer? add in $interval as a parameter.

Note: Although you will find in this sample that we have $http directly on the Controllers, I only did that to simplify the sample. In the real world, you want to add all your $http calls on a User-Defined Service. User Defined Services are not part of this post. Maybe in a future post?


Modules provide a scope and defines your application. All controllers belong to a module, and as a good side-effect, it prevents your controller from belonging to the global scope. You’ll notice that the whole unit “Patients” is one big Module.

Things to think about

  • Angular, obviously isn’t secure. Minification can help in sort of encrypting things, but really, anyone can look at your Javascript from the browser. Therefore you always have to ask yourself: Even if Angular is capable of doing this specific logic that I want it to do, do I want Angular to do it, or just leave it for ASP.NET server-side? On that same note, how much work do you want Angular to do and how much do you want to pass on to the Server?
  • Consistency is very important in a maintainable code. Now, although not discussed in this post, Angular can also take care of Routes. Do you want Angular to handle Routes, or would you rather have ASP.NET handle it?

Added Reference:


Fun with Javascript Functions

A maintainable code means having recurring themes that allows it to have a predictable format thereby making it maintainable. In the past design patterns were regarded as “a thing” only for Server-Side codes: But as web applications become more modern, the more we need Javascript and the more we need to keep our codes pretty.

In this post, we’ll discuss some very basic patterns that we can use for Javascript functions

  • Functions as Abstractions
  • Functions to build modules
  • Functions to avoid Global variables

About the Codes

You can find the codes in It might come as confusing if you try to run the codes and nothing’s happening. Everything that’s happening is happening in the Console, so to see them in action you would want to hit F12 on your browser to see the Developer Tools. The main page index.html is just there to have somewhere to run the scripts on.


You can choose not to run certain scripts from the project by disabling the script tags that you’re not interested in.

Functions as Abstractions

I want to do some work and I want to wrap it all up in a function and assign it to a variable

var work = function () {
“Doing Work.”);

We did just that then we called work() … That’s with a parenthesis because it’s a function. That’s cool. Now what I want to do is to add another level of abstraction. I want to add another function. This time I’ll call it doWork and it will accept a function as a parameter.

var work = function () {
”    Doing Work.”);

doWork = function (f) {

“Calling Work…”);
console.log(“Work Called.”);


So now I’ll run doWork and pass in the work function and it’s all good. Take note as well that we’re not passing work() with a parenthesis, because if we do that, it will pass in the result of the function. That’s going to throw an error because work() is not returning anything and we will ultimately be passing an undefined to doWork.

Functions to build Modules

Now, sometimes I need more than just a function. Sometimes I need an object that contains data and has methods attached to it. Let’s see this sample below.

var createWorkerInline = function () {
return {
function () {
“Performing Inline Job “);
// Another inline job can go here

var workerInLine = createWorkerInline();

I created an object named workerInLine and I want it to return an inlineJob which is a function. But here’s a more common approach: Instead of declaring it inline, what I want to do is structure it in a way that gives more focus on my implementation. So I’m going to break it all down.

var createWorker = function () {
var workCounter = 0;
job1 = function () {
console.log(“Performing Job 1. Count ” + workCounter);
job2 = function () {
console.log(“Performing Job 2. Count ” + workCounter);
         task1: job1,
         task2: job2

var worker = createWorker();
worker.workCounter++; // This will not work: Undefined

Here is what’s happening:

  • I have separated the definitions from the return statement: And in the return statement, I told Javascript that task1 will return the function that is assigned to the variable job1 and that task 2 will return the function that is assigned to the variable job2.
  • I can create a variable within createWorker that can be shared within the scope. You’ll notice that I created a counter. I increment this counter everytime the job is called. I display the current value evertime on the console
  • Because the counter (much like job1 and job2) is not part of the return statement, it will remain private. Accessing it from outside the scope will not work. Funny enough, it doesn’t throw an error either.

Also referred to as the Revealing Module Pattern. We encapsulate some codes inside a function which is the definition of a module in a general sense in Computer Science. We’re creating a module in Javascript by creating a function and inside of that function we’re building up some things that we can expose to the outside world

Functions to Avoid Global Variables

If you know a little bit about programming, you’ll know that global variables are bad. They easily become a source of confusion and bugs. Because Javascript is a dynamically-typed language,  heavily typed language, it’s very easy for me to override a global variable and now we’re lost of who accessed what.

All the activities we have done thus far has been on a global scope. Here’s a way to not have any globals at all: Using a self-executing function or otherwise known as an Immediately Invoked Function Expression (IIFE, pronounced as “iffy”) which is an anonymous function that gets invoked as soon as the page loads.

(function() {
// Perform Tasks here

It may look confusing but all it is is an anonymous function surrounded by a parenthesis and then we end it with an open/close parenthesis thereby telling Javascript to invoke this now.

Node.js for .NET Developers


You can pick up the solution from

This whole post is a good introduction to Node.js from a .NET Developer’s perspective. By the end of this document, you should

  • Be familiar with Node.js
  • Get your hands wet with Node.js JavaScript
  • Be abel to build a very basic HTML Hello World website
  • Be able to build an API

We will not build anything too pretty because as i’d like to limit the scope of this post, but we will be able to create a HTML Website and a WebAPI.

It is assumed that

  • You know your way around Visual Studio
  • You know the basics of a website
  • You have an idea what MVC is

What is it?

The official definition is Node.js® is a JavaScript runtime built on Chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. To explain that further:

  • You write Server-side codes that run on Chrome’s V8 engine. That said, js codes are actually compiled, and only expressed as Javascript. This is in contrast to the Javascript that you would write in a browser, which is interpreted script.
  • You most likely write Client-Side scripts on Javascript, and so you will most likely be dealing with Javascript and JSON both Server-Side and Client-Side
  • Non-blocking IO simply means Asynchronous operations, that is, when you make a request to the server, it doesn’t block any other incoming requests.
  • V8 provides a predictable environment for developers. Unlike Javascript that you write on a browser, Node.js runs on a platform with not much variables that will affect its dependencies.

I am primarily a .NET Developer, and so majority of what will be discussed here is (a) how Node.js compares with ASP.NET and (b) using Visual Studio to code.

Comparing Node.js and ASP.NET

For starters, they both have a dot in their names… Does that count?

  • Asynchronous Operations: Although ASP.NET allows for this, Node.js provides this functionality out of the box
  • Language used: ASP.NET can be expressed using C# or VB, and whatever language is available for .NET, including F#. On the other hand, Node.js is expressed in Javascript.
  • Compilation: Just because Node.js is expressed in Javascript, it means that it’s not compiled and that it’s slower compared to ASP.NET which is compiled into assemblies. Node.js is compiled. Javascript is merely the language used.
  • Power: Node.js, by definition is fast and efficient. However, it is not used for more intensive stuff that require much processing power.
  • Package Manager: While .NET as a whole has Nuget (, Node has NPM ( or Node Package Manager.
  • Engine: ASP.NET uses the .NET Framework as the engine while Node.js uses V8.
  • Views: ASP.NET Provides View Engines with either ASPX or Razor available out of the box. They’re pretty much the same with very little difference in syntax. In Node.js, we work with View Engines that we can get from NPM. Since you’re reading a blog for .NET Developers, it’s best to use Vash, being a Razor clone.

Let’s start!

Starting Node.js

Getting Node.js

Downloading for Usage

We can download Node.js from It will detect your machine for you. You can go ahead and download what link is available, or go to for more options.

Preparing your development from Visual Studio

From Visual Studio, create a New Project and you’ll find Node.js Web Application from the Templates list under JavaScript. This should get you started with a Web Server running.


Note: Please make sure you download the package from, otherwise Visual Studio will hang up when you create a new Project.

What you’re getting

Now, let’s see what Visual Studio created for you.

‘use strict’;
http = require(‘http’);
port = process.env.PORT || 1337;
http.createServer(function (req, res) {
200, { ‘Content-Type’: ‘text/plain’ });
res.end(‘Hello World\n’);

You get a port that Nodejs opens for you and a createServer method that accepts self-executing method.

It writes Hello World in the Response as a plain text, which you can easily replace with an application/json if you’re doing a WebAPI.

Let’s go through them in the next sub sections

Running from the Console

You’ll notice that a console is running everything: It’s just opening a port an accepting a request and returning something. If you’re running on production , there are a few solutions out there that will allow you to install it as a service, like os-service ( and node-windows (

You’ll also notice that it’s starting up from server.js: You can find that this file is set in the package.json file located in the root folder of your project

“name”: “node-js.aspnet-nodejs”,
“version”: “0.0.0”,
“description”: “NodeJs.AspnetNodejs”,
“main”: “server.js”,
“author”: {
“name”: “John”


Now, dependencies. In .NET (and most other frameworks out there), it is the framework that handles the dependencies by looking at the folder structure and going through each file and looking at the classes available.

Node.js is quite different in that it expects you to point to it where the dependencies are, sort of like how C++ works. Here, it’s via the require keyword and in the sample above it’s using the http module.

How to Point to your Dependencies

Here’s an introduction on how to use the require/exports keyword to link them all up. Here’s what my project looks like


I created a folder named modules. That’s where I want to put all my custom methods. I can group files that are relevant to each other based on what they do, and even put them in the root folder. But for the purpose of this blog, I used a straightforward name.

Under it, I created a numberSquared and a personInfo file. They’re javascript files, as opposed to cs or vb if you’re coming from .NET. We will call these exposed objects from our server.js.


I want my personInfo to return a static value, and so I’m going to use the exports keyword and return an anonymous class to a named field that i’m going to call person.

module.exports.person = { id: 0, firstName: “John Conrad”, lastName: “Domingo” };

Back at server.js, I say

// Require: Field
var staticPersonInfo = require(‘./modules/personInfo.js’);
console.log(‘Test >> Default Person is ‘ + JSON.stringify(staticPersonInfo.person));

Where I just call .person like a normal field.


It’s pretty much the same concept for methods, but this time I’m going to tell the exports keyword to take a self-executing anonymous method and say that squared will return the number * number.

module.exports = function (number) {
return { squared: function () {
return number * number;

Back at server.js I do the same thing by requiring a numberSquared and this time, I will get 25 by calling the squared() method.

// Require: Method
var simpleMath = require(‘./modules/numberSquared.js’);
console.log(‘Test >> The square of 5 is ‘ + simpleMath(5).squared());

Method Structure

You will find that the default method structure of self-executing methods come in the form of request/response: And that’s because of the asynchronous nature of Node.js. It doesn’t hang around to wait for things to finish. It lets go of control and executes the callback once it does its job.


This section will use the package express ( as an example. Express is a web framework that we will be using later on.

Getting Packages

You can pick up Packages from npm where the command options get installed along with Node.js. You can visit the site on You can easily access the Package Manager from the command prompt. This is the .NET equivalent of Nuget where you can download Packages via Powershell.

To install from Visual Studio using the Command Prompt, Right-click on your project and choose Open Command Prompt here. Or you can just go to the Command Prompt yourself and manually go your project folder. and type

npm install express –save

where express is the name of the package that you want to install and –save says that you want to add express as a dependency to the package.json file, allowing it to automatically be downloaded.

You can also do it via Visual Studio. From the npm node in Solution Explorer, right-click and choose Install New npm Packages.

Either method you choose, you will find that a folder named node_modules will be populated by the package that you installed as well as its dependencies.

Using Packages

To use a package, simply refer to it via the require keyword. Easy! Node.js should already know all about your dependencies since it’s already in your package.json file. Visual Studio even lists your packages from the NPM package properties under Solution Explorer.

var express = require(‘express’);

At this point, even Visual Studio offered express to me via Intellisense


Now, we’re going to make an API. You know that an API is merely a Controller and that if we want to build a website out of that, we’ll basically reuse this method and chuck in a View and Controllers

Refer to the codes below. I once again used the require keyword and pulled in express. Express has functions that corresponds to HTTP verbs, like get, post and delete. And from there, we add in self-executing methods that returns either a HTML string for a website or json (plus xml, potentially).

This set how your calls to the server is routed. You should be very familiar with this as we have it either in RouteConfig in MVC or as attribute on top of the HTTP methods inside your controller.

var http = require(‘http’);
express = require(‘express’);
app = express();

// Default
app.get(‘/’, function (req, res) {
‘<html><head></head><body><h1>Hello World</h1></body></html>’);

// Api
app.get(‘/api/defaultPerson’, function (req, res) {
var staticPersonInfo = require(‘./modules/personInfo.js’);
res.set(“Content-Type”, “application/json”);

var server = http.createServer(app);
server.listen(1337, function () {
“Express is running on port 1337”);

you will notice that from the default get, I passed in HTML. You can in theory build a website out of this, although things would just get silly if you do anything more than a hello world. What you want to do is get a View Engine later on.


Now let’s look at the API. I go to api/default and it’s giving me back a json with the person object I pulled in from personInfo.js. Have a look at the header that I added in.


If we have a look at the header, it is indeed giving us an application/json as we have defined.


There isn’t much parsing either, because Node.js is already talking json in the backend!


That folks, has been your introduction to Node.js. If you are a .NET developer, this post should be very straightforward to you. If you would like to learn more, it would really help if you do further reading on

  • How Node.js handles the MVC pattern
  • How View Engines get integrated (see: Vash)
  • How Node.js links to static resources
  • How Node.js handles data management (see: MongoDB)

IoC with Autofac and Controllers


Our Goal

What I’d like to do now is to use an IoC container for our MVC application. Our goal is to be able to create a concrete object: We want to instantiate the object once in code and pass it along: Instead of going through all the Controllers and manually going


What we have above would generally work: the downside is that

  • We need a reference to all the dependencies of the Concrete Object on compile time instead of on runtime.
  • If we want our Controllers to be fully testable and more easily extendable, we need to type the same *if null, then instantiate* on all the Controllers. This may not sound too bad, but having to do them with a million objects in a million Controllers would just be all messy. We can rid of this problem if we instantiate by code only in one area

Using Autofac

Pick up the sample in

We’re using Autofac. I prefer to use it because

  • It has excellent support
  • Very easy to use compared to others
  • Many people use it which equates to a bigger community

Other folks might be put off with Autofac because of not having much control as opposed to, say, Ninject where you get to change most of the action in your project… As long as you know what you’re doing.

On the flip side, keep in mind that Autofac is Open Source, so you can pick up the source codes in modify it if it does something that you’re not happy with.

Get the Necessary References

Pick up your References from Nuget. For our sample, you’re going to need Autofac.Mvc. If you’re picking it up from within Visual Studio it will also get the main Autofac package for you



Create the Interfaces and concrete objects that need to be passed around. We’ll pick up the Webserver from our Web.Config. This is just to show you that you can instantiate and do whatever you want from the startup of your application.

public interface IWebConfiguration
string WebServer { get; set; }

public class ConcreteObjectConfiguration : IWebConfiguration
public string WebServer { get; set; }

Create your Data Module. This module allows you to create your concrete objects and then register them as an implementation of your interface. What Autofac will do then is pass on the object you create here to the constructors that contains your defined interface.

This is a good idea to use for configurations and repositories.

 public class DataModule : Module
private readonly string _webServer;
DataModule(string webServer)
= webServer;
protected override void Load(ContainerBuilder builder)
// Create the Concrete Object
builder.Register(c => new ConcreteObjectConfiguration { WebServer = _webServer}).As<IWebConfiguration>();

Create a call to configure the Container. See that we pass on the WebServer value to the DataModule that we created above.

public class AutofacConfig
public static void ConfigureContainer()
        var builder
= new ContainerBuilder();

builder.RegisterSource(new ViewRegistrationSource());
builder.RegisterModule(new DataModule(ConfigurationManager.AppSettings[“WebServer”]));
var container = builder.Build();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

Now, call AutofacConfig from Global.asax

protected void Application_Start()
// Call Here.


And you’re all set. From here, you can now use ConcreteObjectConfiguration on all your controllers. Notice below that we don’t even have an empty constructor. Without an IOC container, you can’t do that as it will throw you an error saying you need a parameter-less constructor

public class HomeController : Controller
public IWebConfiguration InjectedConfiguration { get; set; }
public HomeController(IWebConfiguration injectedConfiguration)
= injectedConfiguration;
public ActionResult Index()
= $“The Webserver is in {InjectedConfiguration.WebServer}”;

The object we created earlier will be passed to your constructor, and therefore we can do whatever we want with it. I chose to assign it to a public property so that

  • We can create a Unit Test for the Controller
  • We can use the concrete object for all of the Actions.

Here’s what it looks like now


Scheduling SSRS with Dynamic Dates

You can schedule SSRS Reports, via Subscriptions, but the issue is that you can easily set custom parameters except the date.

This became a problem for me because:

  • I want the users to pick a Start Date and End Date when they open the report. I don’t want it to default to anything because it minimises the reusability
  • I want to schedule the reports to automatically generate for the previous month. SSRS doesn’t allow me to do that from the My Subscriptions page

From the SSRS Home Page, look at the upper-right corner and click on My Subscriptions. This will open up your scheduled reports. In the screenshot below, you’ll notice that you can choose from a list: Any list, that is, including dynamically-loaded ones. This limitation forces you to type in a static date, which defeats the purpose of scheduling if you want your users to always pick a date when they run the same report themselves.


Here’s how I went around the limitation:


  • Create the Dynamic Dates: I created date parameters that will hold the actual date and time used by the report. Make sure they’re hidden, so the user won’t see them.


  • Create the parameter that will tell the report whether to use the Dates entered by the user, or the one that we want to override it with. It will make more sense on the next bullet point.


Make sure it’s an integer and that it’s hidden, so the user won’t see it.


Set the default value to 0


  • Create a new Shared Dataset with this Query. In my project, i named it dsDateRange

  DECLARE @mStartDate DATETIME = @StartDate
  DECLARE @mEndDate DATETIME = @EndDate

  if @DateRange = 1
    — Last Month

    SET @mStartDate = DATEADD(m,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()), 0))
    SET @mEndDate = DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0))
  SELECT @mStartDate AS StartDate, @mEndDate AS EndDate

We set the default value of @mStartDate and @mEndDate to what the users selected by default. Now, let’s look at @DateRange: If the date range is 0, then do nothing. If the @DateRange is 1, then we set @mStartDate and @mEndDate for the first and last date of last month respectively. Now, you can do whatever you want with what the @DateRange corresponds with.

  • Set @mStartDate and @mEndDate with the values from the Dataset.


@mStartDate and mEndDate will always get a value depending on @DateRange. If it is opened by the user, it will all be invisible to them and it will have a default value of 0.

Looking at Subscriptions

Now, if you’ll go to My Subscriptions, you will find that you have the Date Range, mStartDate and mEndDate. Set Date Range to 1, indicating that we want to use our custom Data Set code. Also set mStartDate and mEndDate to Default.


Now you’re good to go.

  • Use @mStartDate in your Datasets and text fields instead of @StartDate.



You can make scheduling prettier by instead of making the Date Range an integer, make it a selection from a list. Make another Dataset. This will consist of a Value and a Label.


Keep the @DateRange an integer, but on the Available Values, choose the Dataset that we just created.


Getting Started with ASP.NET Core

What is it?

ASP.NET Core is an open source web framework for building modern web applications that can be developed and run on Windows, Linux and the Mac. It includes the MVC framework, which now combines the features of MVC and Web API into a single web programming framework.

What You Need

Creating from the Visual Studio Template

From File > New > Project, you will see the .NET Core template. For this quick blog, i chose the Web Application. MVC pattern is obviously a default.


If you instead go to the Web Section, you will have these templates

  • NET Web Application – the ASP.NET application templates you’ve known and used
  • NET Core Web Application (.NET Core) – This will start you with a cross-platform compatible project that runs on the .NET Core framework
  • NET Core Web Application (.NET Framework) – This starts a new project that runs on the standard .NET Framework on Windows

What You’ll Notice

  • Restructure: Core is supposed to be a much smaller and modular: And so you’ll notice
  • Lightweight: Web Applications, whether it be the legacy Webforms, or MVC has been a hog in the last few releases as Microsoft likes to showcase what you can do out of the box. That’s all good, except that if you don’t do a lot of cleanup, you’ll end up with deploying a lot of stuff to production that you don’t really need
  • Initial Download of Packages: Yes, it’s modular and that’s probably the first thing you’ll notice as you create a project. It will pick up the necessary Nuget packages for you. That tells you that these packages aren’t tightly integrated with the framework much like System.Web is.
  • Change in Visual Studio files: You’ll notice that .csproj has been replaced by project.json. It was done this way to make development in Mac a first class citizen. It also makes it easier to modify the project options because it’s json. The same is true with every other files that used to be exclusively associated with Visual Studio

My first ASP.NET Core Application


Entity Framework Code First

What is it?

Entity Framework is a relational mapper that allows you to create your database schema by starting with your models and telling the ORM how each component should be created as well as how they’re related to each other. It is primarily used as a facilitator of Domain-Driven Design, but more on that later. Maybe.

Why use Code First?

Based on my experience, it allows for

  • More control over your database and models: You can practically create your database in a very few lines
  • Not having to worry about creating your database. You just have to know where the server is and which rights you should give your solution. In the end it all comes down to ease of deployment
  • Not having to worry about your SQL Statements. You will mostly be using LINQ, which (I  hope) you’re already using anyway. Saving your changes is as easy as calling SaveChanges();

Why it’s not for you

  • Starting out can be a bit of a pain, as there’s a steep learning curve.  Like really, especially when creating your database. It throws out error messages that doesn’t even match what the issue is. You just have to overcome that initial struggle, then it’s smooth sailing.
  • Although it’s a good thing to not having to worry about SQL Statements, it can also work against you depending on your habits as a programmer but if you have proper unit tests, you should be fine.

Getting Started

We’re using a Patient Management System for a sample. All it does is take the name and time on a table with a constraint and display the same data just to prove that we can insert and read. Grab my sample code here:

This sample uses Entity Framework  6.1.3

Basic Components

Entities: The coded representation of database tables

We’re using Patient and Appointment.

public class Patient
  public Patient()
       PatientAppointments = new List<Appointment>();
   public int PatientId {get;set; }
   public string PatientName { get;set; }

   public virtual ICollection<Appointment> PatientAppointments{ get;set; }

Each patient can potentially contain multiple Appointments. And this relationship is defined by the ICollection in the parent. Notice the PatientAppointments in the Patient class.

public class Appointment
    public int AppointmentId { get; set; }
    public DateTime AppointmentDateTime { get; set; }

You’ll notice that the table looks like a regular class: And that’s the beauty of it all. We isolate the database part and just focus on our object. Now here’s where we

Entity Mapping

Now here’s where we tell EF the attributes of the fields such as

  • The Primary Keys
  • If they’re mandatory or optional fields
  • Max Length
public class PatientMap : EntityTypeConfiguration<Patient>
    public PatientMap()
        // Key
        HasKey(k => k.PatientId);

        // Properties
        Property(p => p.PatientId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
        Property(p => p.PatientName).IsRequired().HasMaxLength(50);

        // To Table

  • The table name that they correspond to
public class AppointmentMap : EntityTypeConfiguration<Appointment>
        public AppointmentMap()
            // Key

            HasKey(k => k.AppointmentId);

            // Properties
            Property(p => p.AppointmentId).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
            Property(p => p.AppointmentDateTime).IsRequired();

            // To Table

The DB Context

This is our representation of the Database. Here we define

  • The Database name
  • Which tables we want to include in our database
  • The mapping classes that we defined earlier
  • Other configs
public class PatientManagementDatabase : DbContext
    public PatientManagementDatabase() : base("PatientManagementContext")
        Configuration.LazyLoadingEnabled = true;
        Configuration.ProxyCreationEnabled = false;

    public DbSet<Patient> Patient { get; set; }
    public DbSet<Appointment> Appointment { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
        modelBuilder.Configurations.Add(new AppointmentMap());
        modelBuilder.Configurations.Add(new PatientMap());

Create Datasource

This is where we put everything together: We tell EF how to create the database. You decide where to call this method: Beginning of your application? App_Start?  Either way, it should be safe to call it anytime because within the initialiser you tell the framework when to create.

private static void CreateDatasource()
    Database.SetInitializer(new CreateDatabaseIfNotExists<PatientManagementDatabase>());

    var context = new PatientManagementDatabase();


That’s it! Now, we just play around with it by LINQ. This is a very simple example that you can build your more complex applications from.

You can download the sample from