Building ASP.NET Core MVC Application Using EF Core and ASP.NET Core 1.0

Introduction

In this article, we will explain how to build the Applications with an ASP.NET Core MVC & Entity Framework Core, using ASP.NET Core 1.0.

Before reading this article, you must read the articles given below for ASP.NET Core knowledge.

Model class

We are going to create a registration page, using ASP.NET Core & EntityFrameWork Core. The Model class given below contains the properties of Registration details in our Applications.

using System;
namespace RegistrationForm.Models
{
    public class Registration
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string Location { get; set; }       
        public string Mobile { get; set; }       
        public string Email { get; set; }      
        public string Address { get; set; }
    }
}

Dependency required

The dependency given below is required to build ASP.NET Core MVC & EntityFrameWork Core Application

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.Design": "1.1.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }
  }
}

Tools required

Add the Entity Framework Core tools in our Application.

"tools": {
  "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
  "Microsoft.EntityFrameworkCore.Tools": {
    "version": "1.0.0-preview2-final",
    "imports": [
      "portable-net45+win8+dnxcore50",
      "portable-net45+win8"
    ]
  }
}

Configuring ASP.NET MVC in ASP.NET Core 1.0

We are going to add "UseMvc" Middleware and "AddMvc()" Configure Services in Startup.cs Class. The code given below clearly mentions that manually we need to add our controller name and an action name in "MapRoute". We can change this controller name and action name, which is based on our requirement in the Application

app.UseMvc(config =>
{
    config.MapRoute(
        name: "Default",
        template: "{controller}/{action}/{id?}",
        defaults: new { controller = "Home", action = "Home" }
    );
});

LocalDB configuration in ASP.NET Core 1.0

In the previous versions, everything is handled by Web. Config but in ASP.NET Core, the connection string is written in the appsettings.json file. By default, it will show as a LocalDB pat,h, and as per our requirement, we can change the connection string path.

The setting JSON file contains the LocalDB connection string details in our Application and we have given the database name "RegDB". If you want to know more about JSON file configuration in ASP.NET Core, please check our previous article Adding A Configuration Source File In ASP.NET Core 1.0.

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=RegDB;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

DbContext in ASP.NET Core 1.0

The code given below contains information about EntityFrameWork Core DbContext. We can add the LocalDB connection string details with the help of the "UseSqlServer" Method.

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
namespace RegistrationForm.Models
{
    public class RegContext : DbContext
    {
        private IConfigurationRoot _config;
        public RegContext(IConfigurationRoot config, DbContextOptions options) : base(options)
        {
            _config = config;
        }
        public DbSet<Registration> Registrations { get; set; }
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            base.OnConfiguring(optionsBuilder);
            optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);
        }
    }
}

Seed data in entity framework core

We are going to implement Code First Migrations in an Entity Framework Core to seed the database with the test data and manually we are entering the seed data information in the "RegContextSeedData" class. The code given below contains the default values of the Registration Details Table in our Application.

using System;
using System.Linq;
using System.Threading.Tasks;

namespace RegistrationForm.Models
{
    public class RegContextSeedData
    {
        private RegContext _context;

        public RegContextSeedData(RegContext context)
        {
            _context = context;
        }

        public async Task SeedData()
        {
            if(!_context.Registrations.Any())
            {
                var newReg = new Registration()
                {
                    Id = Guid.NewGuid(),
                    Name = "RajeeshMenoth",
                    Location = "Thuyyam",
                    Mobile = "123456789",
                    Email = "[email protected]",
                    Address = "Menoth Parambil House, Edappal Post, Thuyyam"
                };
                _context.Registrations.Add(newReg);
                await _context.SaveChangesAsync();
            }
        }
    }
}

Repository

The code given below contains the common repository for our Application.

Server-side validation

In the View Model, we implemented the default validations in the Registration page in our Applications.

using System.ComponentModel.DataAnnotations;

namespace RegistrationForm.ViewModels
{
    public class RegistrationViewModel
    {
        [Required]
        public string Name { get; set; }

        [Required]
        public string Location { get; set; }

        [Required]
        [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]
        public string Mobile { get; set; }

        [Required]
        [EmailAddress]
        public string Email { get; set; }

        [Required]
        [StringLength(5000, MinimumLength = 10)]
        public string Address { get; set; }   
    }
}

Controllers

In our Applications, we created two Controllers, where one is Home and another is Registration.

Home controller

Home Controller returns all the registered user information on the home page with the help of a common repository.

using Microsoft.AspNetCore.Mvc;
using RegistrationForm.Models;
namespace RegistrationForm.Controllers.WebApp
{
    public class HomeController : Controller
    {
        private IRegRepository _repository;
        public HomeController(IRegRepository repository)
        {
            _repository = repository;
        }
        public IActionResult Home()
        {
            var data = _repository.GetAllRegistrations();
            return View(data);
        }
    }
}

Registration controller

The registration controller contains the registration information in our Application.

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using RegistrationForm.Models;
using RegistrationForm.ViewModels;
using System;

namespace RegistrationForm.Controllers.WebApp
{
    public class RegistrationController : Controller
    {
        private RegContext _context;
        private ILogger<Registration> _logger;

        public RegistrationController(RegContext context, ILogger<Registration> logger)
        {
            _context = context;
            _logger = logger;
        }

        public IActionResult Registration()
        {
            return View();
        }

        public IActionResult Home()
        {
            return View();
        }

        [HttpPost]
        public IActionResult Registration(RegistrationViewModel model)
        {
            ViewBag.SuccessMessage = null;

            if (model.Email.Contains("menoth.com"))
            {
                ModelState.AddModelError("Email", "We don't support menoth Address !!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    Registration regData = new Registration()
                    {
                        Id = Guid.NewGuid(),
                        Name = model.Name,
                        Email = model.Email,
                        Location = model.Location,
                        Mobile = model.Mobile,
                        Address = model.Address
                    };

                    _context.Registrations.Add(regData);
                    _context.SaveChanges();

                    ModelState.Clear();
                    ViewBag.SuccessMessage = "Registered Successfully !!";
                }
                catch (Exception ex)
                {
                    _logger.LogError($" Registration Failure : {ex.Message} ");
                }
            }

            return View();
        }
    }
}

Startup .cs

The class given below contains the complete middleware details in our Applications.

using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using RegistrationForm.Models;
using Microsoft.Extensions.Configuration;

namespace RegistrationForm
{
    public class Startup
    {
        private IConfigurationRoot _config;

        public Startup(IHostingEnvironment env)
        {
            var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json");
            _config = ConfigBuilder.Build();
        }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(_config);
            services.AddDbContext<RegContext>();
            services.AddScoped<IRegRepository, RegRepository>();
            services.AddTransient<RegContextSeedData>();
            services.AddMvc();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env,
            ILoggerFactory loggerFactory, RegContextSeedData seeder)
        {
            loggerFactory.AddConsole();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseStaticFiles();

            app.UseMvc(config =>
           {
               config.MapRoute(
                   name: "Default",
                   template: "{controller}/{action}/{id?}",
                   defaults: new { controller = "Home", action = "Home" }
                   );
           });

            seeder.SeedData().Wait();

        }
    }
}

Project.json

project.json contains the complete picture of dependency in our Applications.

{
  "dependencies": {
    "Microsoft.AspNetCore.Diagnostics": "1.0.0",
    "Microsoft.AspNetCore.Mvc": "1.0.1",
    "Microsoft.AspNetCore.Mvc.TagHelpers": "1.1.1",
    "Microsoft.AspNetCore.Mvc.ViewFeatures": "1.1.1",
    "Microsoft.AspNetCore.Server.IISIntegration": "1.0.0",
    "Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
    "Microsoft.AspNetCore.StaticFiles": "1.1.0",
    "Microsoft.EntityFrameworkCore.SqlServer": "1.0.1",
    "Microsoft.Extensions.Configuration.FileExtensions": "1.0.0",
    "Microsoft.Extensions.Configuration.Json": "1.0.0",
    "Microsoft.Extensions.Logging.Console": "1.0.0",
    "Microsoft.EntityFrameworkCore.Design": "1.1.0",
    "Microsoft.NETCore.App": {
      "version": "1.0.1",
      "type": "platform"
    }
  },
  "tools": {
    "Microsoft.AspNetCore.Server.IISIntegration.Tools": "1.0.0-preview2-final",
    "Microsoft.EntityFrameworkCore.Tools": {
      "version": "1.0.0-preview2-final",
      "imports": [
        "portable-net45+win8+dnxcore50",
        "portable-net45+win8"
      ]
    }
  },
  "frameworks": {
    "netcoreapp1.0": {
      "imports": [
        "dotnet5.6",
        "portable-net45+win8"
      ]
    }
  },
  "buildOptions": {
    "emitEntryPoint": true,
    "preserveCompilationContext": true
  },
  "runtimeOptions": {
    "configProperties": {
      "System.GC.Server": true
    }
  },
  "publishOptions": {
    "include": [
      "wwwroot",
      "web.config"
    ]
  },
  "scripts": {
    "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]
  }
}

Bower.json

The simple way in which we can say Bower is optimized for the front-end in our Applications and it provides the client-side dependencies. For example, Bower manages the components and it contains HTML, CSS, JavaScript, font, or even image files.

{
  "name": "asp.net",
  "private": true,
  "dependencies": {
    "jquery": "~3.1.1",
    "jquery-validation": "~1.16.0",
    "jquery-validation-unobtrusive": "~3.2.6",
    "bootstrap": "~3.2.6"
  }
}

Code first migration

First, we need to find the project location in CLI (Command Line Interface ) and afterward, run the commands given below step by step.

  • "dotnet ef migrations add IntialDB" ( new EntityFrameWork migration )
  • "dotnet ef database update" ( update the EntityFrameWork Core database in ASP.NET Core )

To know more about it, please refer to my previous article by clicking here.

Project structure

The structure given below will be created after the off-migration in ASP.NET Core.

Wwwroot

Picture source: https://rajeeshmenoth.wordpress.com

New tag helpers

We used the latest ASP.NET Core Tag Helpersonn Registration page to access the controller and actions, validation,n, etc.

<div asp-validation-summary="All" class="text-danger"></div>
<label asp-for="Name"></label>
<input asp-for="Name" class="form-control" />
<span asp-validation-for="Name" class="text-danger"></span>
<a asp-controller="Home" asp-action="Home" class="btn btn-info">Cancel</a>

Inject tag helpers

In the way given below, we can inject the Tag Helpers into our Application. Now, create the default "_ViewImports.cshtml" file in the View Folder and add the code given below in that file.

@addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"

Client side validations

The client-side validation is done with the help of Bootstrap & jQuery etc. All these Client-side dependencies are accessed from the bower.json file.

Registration

Output

Home

Reference

See Also

You can download other ASP.NET Core 1.0 source codes from MSDN Code, using the links, mentioned below.

Conclusion

We learned how to build the Applications with ASP.NET Core MVC & an Entity Framework Core, using ASP.NET Core 1.0. I hope you liked this article. Please share your valuable suggestions and feedback.