Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7

Be Sociable, Share!

One of the main new features of ASP.NET 5 is unifying the programming model and combining MVC, Web API, and Web Pages in single framework called MVC 6. In previous versions of ASP.NET (MVC 4, and MVC 5) there were overlapping in the features between MVC and Web API frameworks, but the concrete implementation for both frameworks was totally different, with ASP.NET 5 the merging between those different frameworks will make it easier to develop modern web applications/HTTP services and increase code reusability.

Getting started with ASP.NET 5 MVC 6 Web API & Entity Framework 7

In this post I’ve decided to give ASP.NET 5 – MVC 6 Web API a test drive, I’ll be building a very simple RESTful API from scratch by using MVC 6 Web API and the new Entity Framework 7, so we will learn the following:

Using the ASP.NET 5 empty template to build the Web API from scratch.

Overview of the new project structure in VS 2015 and how to use the new dependency management tool.

Using EF 7 commands and the K Version Manager (KVM) to initialize and apply DB migrations.

To follow along with this post you need to install VS 2015 preview edition or you can provision a virtual machine using Azure Images as they have an Image with VS 2015 preview installed.

Step 1: Creating an empty web project

Open VS 2015 and select New Web Project (ASP.NET Web Application) as the image below, do not forget to set the .NET Framework to 4.5.1. You can name the project “Registration_MVC6WebApi”.

Now we’ll select the template named “ASP.NET 5 Empty” as the image below, this template is an empty template with no core dependencies on any framework.

Step 2: Adding the needed dependencies

Once the project is created you will notice that there is a file named “project.json” this file contains all your project settings along with a section for managing project dependencies on other frameworks/components.

We’ve used to manage packages/dependencies by using NuGet package manager, and you can do this with the new enhanced NuGet package manager tool which ships with VS 2015, but in our case we’ll add all the dependencies using the “project.json” file and benefit from the IntelliSense provided as the image below:

So we will add the dependencies needed to configure our Web API, so open file “project.json” and replace the section “dependencies” with the section below:

1

2

3

4

5

6

7

8

9

"dependencies":{

"Microsoft.AspNet.Server.IIS":"1.0.0-beta1",

"EntityFramework":"7.0.0-beta1",

"EntityFramework.SqlServer":"7.0.0-beta1",

"EntityFramework.Commands":"7.0.0-beta1",

"Microsoft.AspNet.Mvc":"6.0.0-beta1",

"Microsoft.AspNet.Diagnostics":"1.0.0-beta1",

"Microsoft.Framework.ConfigurationModel.Json":"1.0.0-beta1"

}

The use for each dependency we’ve added as the below:

Microsoft.AspNet.Server.IIS: We want to host our Web API using IIS, so this package is needed. If you are planning to self-host your Web API then no need to add this package.

EntityFramework & EntityFramework.SqlServer: Our data provider for the Web API will be SQL Server. Entity Framework 7 can be configured to work with different data providers and not only relational databases, the data providers supported by EF 7 are: SqlServer, SQLite, AzureTableStorage, and InMemory. More about EF 7 data providers here.

EntityFramework.Commands: This package will be used to make the DB migrations command available in our Web API project by using KVM, more about this later in the post.

Microsoft.AspNet.Mvc: This is the core package which adds all the needed components to run Web API and MVC.

Microsoft.AspNet.Diagnostics: Basically this package will be used to display a nice welcome page when you request the base URI for the API in a browser. You can ignore this if you want, but it will be nice to display welcoming page instead of the 403 page displayed for older Web API 2.

Microsoft.Framework.ConfigurationModel.Json: This package is responsible to load and read the configuration file named “config.json”. We’ll add this file in a later step. This file is responsible to setup the “IConfiguration” object. I recommend to read this nice post about ASP.NET 5 new config files.

Last thing we need to add to the file “project.json” is a section named “commands” as the snippet below:

1

2

3

"commands":{

"ef":"EntityFramework.Commands"

}

We’ve added short prefix “ef” for EntityFramework.Commands which will allow us to write EF commands such as initializing and applying DB migrations using KVM.

Step 3: Adding config.json configuration file

Now right click on your project and add new item of type “ASP.NET Configuration File” and name it “config.json”, you can think of this file as a replacement for the legacy Web.config file, for now this file will contain only our connection string to our SQL DB, I’m using SQL Express here and you can change this to your preferred SQL server.

Note: This is a JSON file that’s why we are using escape characters in the connection string.

Step 4: Configuring the ASP.NET 5 pipeline for our Web API

This is the class which is responsible for adding the components needed in our pipeline, currently with the ASP.NET 5 empty template, the class is empty and our web project literally does nothing, I’ll add all the code in our Startup class at once then describe what each line of code is responsible for, so open file Startup.cs and paste the code below:

// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940

app.UseMvc();

app.UseWelcomePage();

}

}

}

What we’ve implemented in this class is the following:

The constructor for this class is responsible to read the settings in the configuration file “config.json” that we’ve defined earlier, currently we have only the connection string. So the static object “Configuration” contains this setting which we’ll use in the coming step.

The method “ConfigureServices” accepts parameter of type “IServiceCollection”, this method is called automatically when starting up the project, as well this is the core method responsible to register components in our pipeline, so the components we’ve registered are:

We’ve added “EntityFramework” using SQL Server as our data provider for the database context named “RegistrationDBContext”. We’ll add this DB context in next steps.

Added the MVC component to our pipeline so we can use MVC and Web API.

Lastly and one of the nice out of the box features which has been added to ASP.NET 5 is Dependency Injection without using any external IoC containers, notice how we are creating single instance scoped instance of our “IRegistrationRepo” by calling
services.AddScoped<IRegistrationRepo,RegistrationRepo>();. This instance will be available for the entire lifetime of our application life time of the request, we’ll implement the classes “IRegistrationRepo” and “RegistrationRepo” in next steps of this post. There is a nice post about ASP.NET 5 dependency injection can be read here. (Update by Nick Nelson to use Scoped injection instead of using Singleton instance because DbContext is not thread safe).

Lastly the method “Configure” accepts parameter of type “IApplicationBuilder”, this method configures the pipeline to use MVC and show the welcome page. Do not ask me why we have to call “AddMvc” and “UseMvc” and what is the difference between both 🙂 I would like to hear an answer if someone knows the difference or maybe this will be changed in the coming release of ASP.NET 5. (Update: Explanation of this pattern in the comments section).

Step 5: Adding Models, Database Context, and Repository

Now we’ll add a file named “Course” which contains two classes: “Course” and “CourseStatusModel”, those classes will represents our domain data model, so for better code organizing add new folder named “Models” then add the new file containing the the code below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

usingSystem;

usingSystem.ComponentModel.DataAnnotations;

namespaceRegistration_MVC6WebApi.Models

{

publicclassCourse

{

publicintId{get;set;}

[Required]

[StringLength(100,MinimumLength=5)]

publicstringName{get;set;}

publicintCredits{get;set;}

}

publicclassCourseStatusModel

{

publicintId{get;set;}

publicstringDescription{get;set;}

}

}

Now we need to add Database context class which will be responsible to communicate with our database, so add new class and name it “RegistrationDbContext” then paste the code snippet below:

Basically what we’ve implemented here is adding our Courses data model as DbSet so it will represent a database table once we run the migrations, note that there is a new method named “OnConfiguration” where we can override it so we’ll be able to specify the data provider which needs to work with our DB context.

In our case we’ll use SQL Server, the constructor for “UseSqlServer” extension method accepts a parameter of type connection string, so we’ll read it from our “config.json” file by specifying the key “Data:DefaultConnection:ConnectionString” for the “Configuration” object we’ve created earlier in Startup class.

Note: This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.

Lastly we need to add the interface “IRegistrationRepo” and the implementation for this interface “RegistrationRepo”, so add two new files under “Models” folder named “IRegistrationRepo” and “RegistrationRepo” and paste the two code snippets below:

IRegistrationRepo Code

1

2

3

4

5

6

7

8

9

10

11

12

13

14

usingSystem;

usingSystem.Collections;

usingSystem.Collections.Generic;

namespaceRegistration_MVC6WebApi.Models

{

publicinterfaceIRegistrationRepo

{

IEnumerable<Course>GetCourses();

Course GetCourse(intcourseId);

Course AddCourse(Course course);

boolDeleteCourse(intcourseId);

}

}

RegistrationRepo implementation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

usingSystem;

usingSystem.Collections.Generic;

usingSystem.Linq;

namespaceRegistration_MVC6WebApi.Models

{

publicclassRegistrationRepo:IRegistrationRepo

{

privatereadonlyRegistrationDbContext _db;

publicRegistrationRepo(RegistrationDbContext db)

{

_db=db;

}

publicCourse AddCourse(Course course)

{

_db.Courses.Add(course);

if(_db.SaveChanges()>0)

{

returncourse;

}

returnnull;

}

publicboolDeleteCourse(intcourseId)

{

varcourse=_db.Courses.FirstOrDefault(c=>c.Id==courseId);

if(course!=null)

{

_db.Courses.Remove(course);

return_db.SaveChanges()>0;

}

returnfalse;

}

publicCourse GetCourse(intcourseId)

{

return_db.Courses.FirstOrDefault(c=>c.Id==courseId);

}

publicIEnumerable<Course>GetCourses()

{

return_db.Courses.AsEnumerable();

}

}

}

The implementation here is fairly simple, what worth noting here is how we’ve passed “RegistrationDbContext” as parameter for our “RegistrationRepo” constructor so we’ve implemented Constructor Injection, this will not work if we didn’t configure this earlier in our “Startup” class.

Step 6: Installing KVM (K Version Manager)

After we’ve added our Database context and our domain data models, we can use migrations to create the database, with previous version of ASP.NET we’ve used NuGet package manager for these type of tasks, but with ASP.NET 5 we can use command prompt using various K* commands.

What is KVM (K Version Manager)? KVM is a Powershell script used to get the runtime and manage multiple versions of it being on the machine at the same time, you can read more about it here.

Now to install KVM for the first time you have to do the following steps:

1. Open a command prompt with Run as administrator.
2. Run the following command:

3. The script installs KVM for the current user.
4. Exit the command prompt window and start another as an administrator (you need to start a new command prompt to get the updated path environment).
5. Upgrade KVM with the following command:

1

KVMupgrade

We are ready now to run EF migrations as the step below:

Step 7: Initializing and applying migrations for our database

Now our command prompt is ready to understand K commands and Entity Framework commands, first step to do is to change the directory to the project directory. The project directory contains the “project.json” file as the image below:

So in the command prompt we need to run the 2 following commands:

1

2

kefmigrationaddinitial

kefmigrationapply

Basically the first command will add migration file with the name format (<date>_<migration name>) so we’ll end up having file named “201411172303154_initial.cs” under folder named “Migrations” in our project. This auto generated file contains the code needed to to add our Courses table to our database, the newly generated files will show up under your project as the image below:

The second command will apply those migrations and create the database for us based on the connection string we’ve specified earlier in file “config.json”.

Note: the “ef” command comes from the settings that we’ve specified earlier in file “project.json” under section “commands”.

Step 8: Adding GET methods for Courses Controller

The controller is a class which is responsible to handle HTTP requests, with ASP.NET 5 our Web API controller will inherit from “Controller” class not anymore from “ApiController”, so add new folder named “Controllers” then add new controller named “CoursesController” and paste the code below:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

usingMicrosoft.AspNet.Mvc;

usingRegistration_MVC6WebApi.Models;

usingSystem;

usingSystem.Collections.Generic;

namespaceRegistration_MVC6WebApi.Controllers

{

[Route("api/[controller]")]

publicclassCoursesController:Controller

{

privateIRegistrationRepo _registrationRepo;

publicCoursesController(IRegistrationRepo registrationRepo)

{

_registrationRepo=registrationRepo;

}

[HttpGet]

publicIEnumerable<Course>GetAllCourses()

{

return_registrationRepo.GetCourses();

}

[HttpGet("{courseId:int}",Name="GetCourseById")]

publicIActionResult GetCourseById(intcourseId)

{

varcourse=_registrationRepo.GetCourse(courseId);

if(course==null)

{

returnHttpNotFound();

}

returnnewObjectResult(course);

}

}

}

What we’ve implemented in the controller class is the following:

The controller is attribute with Route attribute as the following
[Route("api/[controller]")] so any HTTP requests that match the template are routed to the controller. The “[controller]” part in the template URL means to substitute the controller class name, minus the “Controller” suffix. In our case and for “CoursesController” class, the route template is “api/courses”.

We’ve defined two HTTP GET methods, the first one “GetAllCourses” is attributed with “[HttpGet]” and it returns a .NET object which is serialized in the body of the response using the default JSON format.

The second HTTP GET method “GetCourseById” is attributed with “[HttpGet]“. For this method we’ve specified a constraint on the parameter “courseId”, the parameter should be of integer data type. As well we’ve specified a name for this method “GetCourseById” which we’ll use in the next step. Last thing this method returns object of type IActionResult which gives us flexibility to return different actions results based on our logic, in our case we will return HttpNotFound if the course does not exist or we can return serialized JSON object of the course when the course is found.

Lastly notice how we are passing the “IRegistrationRepo” as a constructor for our CoursesController, by doing this we are implementing Constructor Injection.

Step 9: Adding POST and DELETE methods for Courses Controller

Now we want to implement another two HTTP methods which allow us to add new Course or delete existing one, so open file “CoursesController” and paste the code below:

Add new HTTP POST method which is responsible to create new Course, this method accepts Course object which is coming from the request body then Web API framework will deserialize this to CLR Course object.

If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code and an object containing description of the validation error. Thanks for Yishai Galatzer for spotting this out because I was originally returning response of type “text/plain” always regarding the “Accept” header value set by the client. The point below contains the fix.

If the course object is not valid (i.e. course name not set) then we’ll return HTTP 400 status code, and in the response body we’ll return an instance of a POCO class(CourseStatusModel) containing fictional Id and description of the validation error.

If the course created successfully then we’ll build a location URI which points to our new created course i.e. (/api/courses/4) and set this URI in the “Location” header for the response.

Lastly we are returning the created course object in the response body.

Note: I believe that the IhttpActionResult response which got introduced in Web API 2 is way better than IActionResult, please drop me a comment if someone knows how to use IhttpActionResult with MVC6.

That’s all for now folks! I’m still learning the new features in ASP.NET 5, please drop me a comment if you have better way implementing this tutorial or you spotted something that could be done in a better way.

Some comments:
The reason you call UseMvc separately than AddMvc is that AddMvc is where the MVC core services are added to the Dependency Injection system, and UseMvc is where MVC (specifically the routing middleware) is added to the pipeline.

Since DI registration has to be completed before services can be consumed, the registration is broken into two steps.

About IHttpActionResult – We are tracking two issues at the moment for improving action results for Web API scenarios.

Here is what I see, David might have seen something different, you will have to ask him 🙂

When you return the following:
Context.Response.StatusCode = 400;
return new ObjectResult(“Failed to save course”);

You are really not returning Json or a String, instead you ask the content negotiation system to negotiate the result for you. By default this will return a text/plain content type with the string you passed. That’s not a typical approach for writing an API.

So if you want to return Json only, make a POCO class describing the error (say CourseStatus ??) and
Return JsonResult(new CourseStatus(“Failed to save course”));

if you want to always return a string regardless of how the Formatters are set up then you can just return ContentResult(“Failed to save course”);

Another thing to remember (and that is supported in Web API 2.x as well) is that you can just return an object from your method, and can mix objects and action results.

In regards to the usage of action results in your code when you have to set headers and status code before returning the action result itself I believe resolving issue#1 with some more love will prevent the need to setting these extra values. I’m just going to reference this blog in the issue to make sure we covered these scenarios.

@Yishai there was a discussion on Twitter the other day about AddMvc, UseMvc. I think the general sentiment is that one should implicitly cause other to happen. I believe the best solution would be to add a route lambda to AddMvc so that everything MVC specific is configured in one place, and with such setup UseMvc should be called implicitly by the framework and pass that route lambda

Opt in with UseMvc is too verbose IMHO, because 99,9% cases people opt in anyway.

EF6 (and I am assuming EF7) dbcontexts are not thread safe, so registering as a Singleton could cause some pretty weird errors if multiple people hit the WebAPI at once.

I think that the repository also has to be registered as Scoped, otherwise you would get one global instance of the repository that has the same instance of the DbContext even though it as registered as Scoped.

Hopefully some experts can educate us as to the proper registration pattern.

This sure was another interesting one to read and experiment with. Concise and straight forward as usual.
Given comments and opinions were also taken into accounts in my case. Thanks
So I’ve done my tests and managed to achieve what I wanted [got the results I expected… and most of the infos I needed… You were right about EF 7 ; )]

BTW Visual Studio 2015 CTP version is now available on line. It’s downloaded though I haven’t got time to install yet.
Anyone has worked with the new CTP version yet?

Your tutorials have been instrumental for me in becoming acclimated with so many new technologies, such as your Token Authorization series and now this great stuff on ASP MVC 6 and EF7. Keep up the good work…PLEASE!!

About your note “This is not the optimal way to set the connection string, there are MVC6 examples out there using this way, but for a reason it is not working with me, so I followed my way.”

It was happening to me that I was getting a compilation on UseSqlServer on Startup.cs but was able fix it by adding the reference to Microsoft.Data.Entity (using Microsoft.Data.Entity; at the begining of the file) so maybe that was the reason the optimal way didn’t work for you.

When I clone the Github source and try open it in Visual Studio 2015 I get a number of errors pertaining to IConfiguration and IConfigurationSouceContainer. This error in particular is a problem:

The type ‘IConfigurationSourceContainer’ is defined in an assembly that is not referenced. You must add a reference to the assembly ‘Microsoft.Framework.ConfigurationModel.IConfigurationSourceContainer, version 0.0.0.0, Culture=neutral, PublicKeyToken=null’