DotNetCurry Logo

Unified ASP.NET 5 - Using MVC 6, WEB API and Entity Framework 7 in an Application

Posted by: Mahesh Sabnis , on 12/16/2014, in Category ASP.NET MVC
Views: 57134
Abstract: In this article, we will create a simple application using ASP.NET MVC 6 and Entity Framework 7. We will implement this application from scratch using an empty ASP.NET 5 Template.

Visual Studio 2015 Preview comes with some new and exciting enhancements for web development, cloud development and cross-platform mobile development. A prominent change in this release is the unification and combination of MVC, WEB API and Web Pages in a single programming framework called as  MVC 6 which removes the overlap between the three frameworks. Also ASP.NET MVC 6 can now be self-hosted just like Web API 2 and SignalR. Along with these new features, Visual Studio 2015 provides an easy integration with client-side framework like Grunt and Bower. All in all, web development using Visual Studio 2015 is looking smoother than ever.

 

In this article, we will design a simple application using ASP.NET MVC 6 and Entity Framework 7. We will implement this application from scratch using an empty ASP.NET 5 Template. Let’s take a quick overview of what’s new in EF7 and MVC 6 and what we need to know before getting started. This article uses Visual Studio 2015 Ultimate Preview. This can be downloaded from here.

What is ASP.NET 5 and MVC 6?

Editor’s Note: ASP.NET 5 is the .NET stack to create modern web applications. In this stack, you have ASP.NET MVC, WEB API and Web Pages which have been unified and merged into one single unified framework called as MVC 6. Why was this done? ASP.NET offers three frameworks for creating web applications: ASP.NET Web Forms, ASP.NET MVC, and ASP.NET Web Pages. All three frameworks are mature, and you can create web applications with any of them however each has it's own template, which gives a perception to the everyday developer that all these technologies are disjoint and distinct. This is far from true. All these technologies use .NET underneath and share a number of classes in the ASP.NET Core. The unified programming model will change this perception. So in Visual Studio 2015 preview, you will develop an MVC 6 application using ASP.NET 5 Empty project template. Similarly you can create a Web Pages app using the same template. This unification will prove helpful for developers who are developing web applications using a single framework using various pieces of the ASP.NET platform as per the requirements.

Some other highlights of the ASP.NET 5 stack is that it can be run on the .NET Framework OR .NET Core which is a new cloud optimized runtime that supports side-by-side versioning (running multiple versions of .NET frameworks side by side). ASP.NET 5 can also be run on OS X and Linux using the Mono runtime.

Entity Framework has so far focused on relational stores (databases) for providing database table mappings so that the CRUD operations can be handled easily. But application development is changing and the latest version of Entity framework 7 Preview reflects that by focusing on local device data store like SQLite or a non-relational data store like Redis or a cloud storage like Azure Table Storage. Designing data-centric application using these stores also needs an object mapping mechanism like EF provides, so it’s good to see that now EntityFramework provides supports for these stores as well.

ASP.NET MVC 6 comes with some new features as well. Some prominent ones are:

- MVC, WEB API and Web Pages are merged into one single framework.

- Project.json: This is a new file provided to manage all dependencies for a project. All the necessary references for the project need to be mentioned in the file. The necessary reference gets added in the project references when the file is saved.

- Dependency Injection is inbuilt in this version of MVC. This helps to manage all the necessary components (services, models, etc.) in the application for instance creation.

- The Global.asax is replaced by Startup.cs. The Startup class provides methods to register dependency for the application.

- Config.json: This file contains the configuration environment variables e.g. Database Connection string.

  An entire list of what’s new in VS 2015 and .NET 4.6 Preview is over here (now VS Community) https://www.visualstudio.com/vs/community/

ASP.NET MVC 6 and EF 7 Application

Step 1: Open Visual Studio and create a new ASP.NET Empty application with the name ‘ASP5AppWithEF7’. Observe we are choosing an ASP.NET 5 template which is a unified template to create MVC, WebAPI or Web Forms application. Web Pages has not yet been added in the Preview, but will be, when VS 2015 Final version is released:

empty-aspnet

This step will create an ASP.NET Project with the following structure:

aspnet-project-structure

In the above diagram, the References folder shows ASP.NET 5.0 and ASP.NET Core 5.0. This represents the runtimes references supported by the ASP.NET 5.0. This new version supports Full .NET CLR with backward compatibility. The other runtime is Core CLR, which is cloud optimized runtime and is a completely modular runtime for ASP.NET projects. This allows the developer to include only those components which are required for the project. How cool is that!

The target KRE (K Runtime Environment) version supported for the ASP.NET Projects can be found from the project properties as below:

K-runtime

KRE: The K Runtime Environment is a new environment necessary to bootstrap and run the ASP.NET Applications in this version.

Step 2: Sine we will be using the EntityFramework 7 in our application, we need to add the necessary references.  To do so, open Project.json file and in the “dependencies” add the following:

dependencies-json

Thankfully we have intellisense for the packages. Our project requires the following dependencies:

intellisense

By default, we will have ‘Microsoft.AspNet.Server.IIS’ and the following:

- Microsoft.AspNet.Server.IIS - The above package represents the IIS Hosting

- EntityFramework Packages - All packages starting from EntityFramework represents EntityFramework packages

  • EntityFramework.Relational - represents EF components for relational data store
  • EntityFramework.SqlServer - represents EF components for Sql Server database
  • EntityFramework.Migrations - represents EF Code First Migrations. The data table can be generated from the model class.
  • EntityFramework.Commands – provides Command line utility for EF used in DB Migrations.

- Microsoft.AspNet.Mvc - represents ASP.NET MVC, so that applications can use MVC features like WEB API controller class, MVC Controllers etc.

- Microsoft.AspNet.Routing - represents routing features of ASP.NET

- Microsoft.Framework.ConfigurationModel.Json – this package provides methods for reading json files in the project e.g. Config.json

To use the migration commands for DB migrations, we need to add the following section in the Project.json

"commands": {
    "orm": "EntityFramework.Commands"
}

This section will be used when we will migrate the model class to database table. We will be doing the DB Migration using KVM, which is the K Version Manager, for managing multiple version of the framework.

Step 3: To use of Sql Server in our application, create database with the name ApplicationDB.

Step 4: To make connection to the Database during the migration process, we need to define a database connection string. In the project, we already have Config.json file with a Connection string. W need to change it as shown here:

{
    "Data": {
        "DefaultConnection": {
            "ConnectionString": "Server=.;Database=ApplicationDb;Trusted_Connection=True;"
        }
    }
}

Step 5: Open the Startup.cs file and define the property and constructor as shown here:

public static  IConfiguration Configuration { get; set; }

public Startup(IHostingEnvironment hostingEnv)
{
    Configuration = new Configuration().AddJsonFile("Config.json").AddEnvironmentVariables();
}

The IHostingEnvironment mocks Web hosting for the application. The constructor creates an instance of the Configuration class and reads Config.json file. This helps to read the Connection String defined in the file.

Step 6: To define the model for the application with entities and the CRUD operations, add the folder of name Models in the project with the class file as shown here:

using System;

using Microsoft.Data.Entity;
using Microsoft.Data.Entity.Metadata;
using System.ComponentModel.DataAnnotations;

namespace ASP5AppWithEF7.Models
{
    /// <summary>
    /// The Entity class with Product properties
    /// </summary>
    public class Product
    {
        [Key]
        public int ProductId { get; set; }
        public string ProductName { get; set; }
        public string CategoryName { get; set; }
        public string Manufacturer { get; set; }
        public int Price { get; set; }
    }


    /// <summary>
    /// The context class. This uses the Sql Server with the Connection string
    /// defined in the Config.json
    /// </summary>
    public class ProductDbContext : DbContext
    {
        public DbSet<Product> Products { get; set; }

        protected override void OnConfiguring(DbContextOptions options)
        {
            options.UseSqlServer(Startup.Configuration.Get("Data:DefaultConnection:ConnectionString"));
            
        }
    }
}

The above code defines the Product class with properties for the Product information. The important thing to notice here is the ProductDbContext class, which is derived from DbContext class. The OnConfiguration method specifies that SQL Server is used with the connection string for database operations.

Step 7: To implement DB Migration, open the command prompt with Admin Rights and run the following command to use the KVM:

@powershell -NoProfile -ExecutionPolicy 
unrestricted -Command 
"iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/master/kvminstall.ps1'))"

kvm-usage

The above command installs the KVM Script for the current user. Restart the Command prompt and run the following commands to perform the DB Migration:

kvm-upgrade

kvm-initial

The above commands uses the ProductsDbContext class for the migration.

kvm-dbmigration

The k orm migration apply adds the migration files in the project. (Note: The ‘orm’ here is the section which we added in the Project.json file.)

The project will have a new folder of the name ‘Migrations’ as shown here:

migrations

Step 8: To define logic for performing CRUD operations on the Product table, we need to add a folder of the name ‘Services’ in the project with the class file containing the following code:

using System;
using System.Collections.Generic;
using ASP5AppWithEF7.Models;
using System.Linq;
namespace ASP5AppWithEF7.Services
{
    /// <summary>
    /// Interface for defining the methods for performing CRUD operations 
    /// on the Product table
    /// </summary>
    public interface IProductService
    {
        IEnumerable<Product> GetProducts();
        Product GetProduct(int id);
        Product CreateProduct(Product Product);
        Product UpdateProduct(int id, Product Product);
        bool DeleteProduct(int id);
    }
    /// <summary>
    /// The service class containing logic for CRUD operations
    /// </summary>
    public class ProductService : IProductService
    {

        ProductDbContext ctx;

        public ProductService(ProductDbContext c )
        {
            ctx = c;
        }

        public Product CreateProduct(Product Product)
        {
            ctx.Products.Add(Product);
            ctx.SaveChanges();
            return Product;
        }

        public bool DeleteProduct(int id)
        {
            var product = ctx.Products.Where(p => p.ProductId == id).First();
            ctx.Products.Remove(product);
            if (ctx.SaveChanges()>0)
            {
                return true;
            }
            return false;
        }

        public Product GetProduct(int id)
        {
            var product = ctx.Products.Where(p => p.ProductId == id).First();
            return product;
        }

        public IEnumerable<Product> GetProducts()
        {
            return ctx.Products.AsEnumerable();
        }

        public Product UpdateProduct(int id, Product Product)
        {
            var prod = ctx.Products.Where(p => p.ProductId == id).First();

            if (prod != null)
            {
                prod.ProductName = Product.ProductName;
                prod.CategoryName = Product.CategoryName;
                prod.Manufacturer = Product.Manufacturer;
                prod.Price = Product.Price;

                ctx.SaveChanges();
            }
            return prod;
        }
    }
}

The ProductService class implements IProductService interface. The class implements all methods containing EF code first logic for performing CRUD operations.

Step 9: Open Startup class and add the following methods in it:

/// <summary>
/// The below methods performs dependency injection
/// for ProductDbContext and ProductService
/// </summary>
/// <param name="srvs"></param>

public void ConfigureServices(IServiceCollection srvs)
{
    //Entity Framework to use Sql Server
    srvs.AddEntityFramework().AddSqlServer().AddDbContext<ProductDbContext>();
    //MVC so that we can use MVC and Web API
    srvs.AddMvc();
    //The Dependency for the DbContext is added
    srvs.AddScoped<ProductDbContext, ProductDbContext>();

    srvs.AddScoped<IProductService, ProductService>();
}

//Configura the code for Mvc Startup
public void Configure(IApplicationBuilder appBuilder)
{
    appBuilder.UseMvc(r=>r.MapRoute(
         name: "default",
            template: "{controller}/{action}/{id?}",
            defaults: new { controller = "ProductMVC", action = "Index" }
        ));
}

The above code has these specifications:

- ConfigurationServices():

  • This method specifies the use of the EF 7 with SQL Server Connectivity. This defines the use of ProductDbContext class for performing Db Connectivity.
  • The AddMvc() method call specifies that the MVC 6 with WEB API is to be used in the application.
  • The AddScoped() method is used for dependency injection. Currently for the application, dependency injection is done for ProductDbContext and ProductService classes.

- Configure() - The UseMvc() method is used for defining Routing expressions for the MVC application.

 

Step 10: In the project, add a new folder with the name Controllers. In this controller, add a new WEB API Controller class with the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Mvc;
using ASP5AppWithEF7.Services;
using ASP5AppWithEF7.Models;

namespace ASP5AppWithEF7.Controllers.Controllers
{
    [Route("api/[controller]")]
    public class ProductAPIController : Controller
    {

        IProductService service;

        public ProductAPIController(IProductService srv)
        {
            service = srv;
        }


        // GET: api/values
        [HttpGet]
        public IEnumerable<Product> Get()
        {
            return service.GetProducts();
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public Product Get(int id)
        {
            return service.GetProduct(id);
        }

        // POST api/values
        [HttpPost]
        public Product Post(Product prd)
        {
           return service.CreateProduct(prd);
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public Product Put(int id, Product prd)
        {
           return service.UpdateProduct(id, prd);
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public bool Delete(int id)
        {
           return service.DeleteProduct(id);
        }
    }
}

he above class performs CRUD operations using the ProductService class.

Step 11: Run the application and check the ApplicationDb Database. The Product table gets created in it. Add some test data in the Product table. In the address bar of the browser, enter the URL as http://<server>/api/ProductAPI. Doing so will show the Product data:

xml-tree

In the same way, you can add MVC controllers, Views, etc in the project.

Conclusion: ASP.NET 5 is the .NET stack which provides MVC 6, Web API and Web Pages as a single unified programming model to facilitate development of modern Web Applications. With this new ASP.NET 5 template, Microsoft aims at changing the perception of developers and reinforce the idea that these technologies are unified.

Download the entire source code of this article (Github)

Was this article worth reading? Share it with fellow developers too. Thanks!
Share on LinkedIn
Share on Google+
Further Reading - Articles You May Like!
Author
Mahesh Sabnis is a DotNetCurry author and Microsoft MVP having over 17 years of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions). Follow him on twitter @maheshdotnet


Page copy protected against web site content infringement 	by Copyscape




Feedback - Leave us some adulation, criticism and everything in between!
Comment posted by ineffablep on Saturday, January 24, 2015 9:53 AM
How do you deploy this in to Windows Server
Comment posted by Umer Ahmed on Friday, January 30, 2015 4:41 AM
A very good article, I would like to point out that you can introduce .Net distributed cache into this application with minimum effort. NCache a .Net distributed cache provides integration with EF as a feature. Please visit http://www.alachisoft.com/ncache/ for more information.
Comment posted by JDS on Wednesday, February 4, 2015 6:15 PM
Hi Mahesh,

I have found that while the project compiles with VS2015 it does not run. In fact, the KVM module fails citing that 'add initial' is only for an 'existing migration'.

When the project is run the Browser reports 403.14 - Forbidden.

I did create a database entitled 'ApplicationDb' using SQL 2014.
--

Do you have any idea why the project fails?

Thanks,
JDS
Comment posted by rohit on Monday, April 13, 2015 8:26 AM
i got valuable information on webapi and MVC controller which is unified in MVC 6 ..see more on
http://mvc4all.com/mvc/top-10-new-features-in-asp-net-5-and-mvc-6/