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.
  1. using System;  
  2.    
  3. namespace RegistrationForm.Models  
  4. {  
  5.     public class Registration  
  6.     {  
  7.         public Guid Id { getset; }  
  8.    
  9.         public string Name { getset; }  
  10.            
  11.         public string Location { getset; }  
  12.            
  13.         public string Mobile { getset; }  
  14.            
  15.         public string Email { getset; }  
  16.            
  17.         public string Address { getset; }  
  18.     }  
  19. }  
Dependency Required
 
The dependency given below is required to build ASP.NET Core MVC & EntityFrameWork Core Applications.
  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.AspNetCore.Diagnostics""1.0.0",  
  4.     "Microsoft.AspNetCore.Mvc""1.0.1",  
  5.     "Microsoft.AspNetCore.Mvc.TagHelpers""1.1.1",  
  6.     "Microsoft.AspNetCore.Mvc.ViewFeatures""1.1.1",  
  7.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0",  
  8.     "Microsoft.AspNetCore.Server.Kestrel""1.0.1",  
  9.     "Microsoft.AspNetCore.StaticFiles""1.1.0",  
  10.     "Microsoft.EntityFrameworkCore.SqlServer""1.0.1",  
  11.     "Microsoft.Extensions.Configuration.FileExtensions""1.0.0",  
  12.     "Microsoft.Extensions.Configuration.Json""1.0.0",  
  13.     "Microsoft.Extensions.Logging.Console""1.0.0",  
  14.     "Microsoft.EntityFrameworkCore.Design":"1.1.0",  
  15.     "Microsoft.NETCore.App": {  
  16.       "version""1.0.1",  
  17.       "type""platform"  
  18.     }  },  
Tools required
 
Add the Entity Framework Core tools in our Application. 
  1. "tools": {  
  2.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final",  
  3.     "Microsoft.EntityFrameworkCore.Tools": {  
  4.       "version""1.0.0-preview2-final",  
  5.       "imports": [  
  6.         "portable-net45+win8+dnxcore50",  
  7.         "portable-net45+win8"  
  8.       ]  
  9.     }  
  10.   },  
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 Applications.
  1. app.UseMvc(config =>  
  2.            {  
  3.                config.MapRoute(  
  4.                    name: "Default",  
  5.                    template: "{controller}/{action}/{id?}",  
  6.                    defaults: new { controller = "Home", action = "Home" }  
  7.                    );  
  8.            });  
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 appsettings.json file. By default, it will show as a LocalDB path and as per our requirement, we can change the connection string path.
 
The appsetting JSON file contains the LocalDB connection string details in our Application and we have given the database name as "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.
  1. {  
  2.   "ConnectionStrings": {  
  3.     "DefaultConnection""Server=(localdb)\\MSSQLLocalDB;Database=RegDB;Trusted_Connection=True;MultipleActiveResultSets=true"  
  4.   }  
  5. }  
DbContext in ASP.NET Core 1.0
 
The code given below contains an information about EntityFrameWork Core DbContext. We can add the LocalDB connection string details with the help of "UseSqlServer" Method.
  1. using Microsoft.EntityFrameworkCore;  
  2. using Microsoft.Extensions.Configuration;  
  3.    
  4. namespace RegistrationForm.Models  
  5. {  
  6.     public class RegContext : DbContext  
  7.     {  
  8.         private IConfigurationRoot _config;  
  9.    
  10.         public RegContext(IConfigurationRoot config, DbContextOptions options) : base(options)  
  11.         {  
  12.             _config = config;  
  13.         }  
  14.         public DbSet<Registration> Registrations { getset; }  
  15.    
  16.         protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)  
  17.         {  
  18.             base.OnConfiguring(optionsBuilder);  
  19.             optionsBuilder.UseSqlServer(_config["ConnectionStrings:DefaultConnection"]);  
  20.         }  
  21.     }  
  22. }  
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 Registration Details Table in our Application. 
  1. using System;  
  2. using System.Linq;  
  3. using System.Threading.Tasks;  
  4.    
  5. namespace RegistrationForm.Models  
  6. {  
  7.     public class RegContextSeedData  
  8.     {  
  9.         private RegContext _context;  
  10.    
  11.         public RegContextSeedData(RegContext context)  
  12.         {  
  13.             _context = context;  
  14.         }  
  15.    
  16.         public async Task SeedData()  
  17.         {  
  18.             if(!_context.Registrations.Any())  
  19.             {  
  20.                 var newReg = new Registration()  
  21.                 {  
  22.                     Id = Guid.NewGuid(),  
  23.                     Name = "RajeeshMenoth",  
  24.                     Location = "Thuyyam",  
  25.                     Mobile = "123456789",  
  26.                     Email = "[email protected]",  
  27.                     Address = "Menoth Parambil House, Edappal Post, Thuyyam"  
  28.                 };  
  29.                 _context.Registrations.Add(newReg);  
  30.                 await _context.SaveChangesAsync();  
  31.             }  
  32.         }  
  33.     }  
  34. }  
Repository
 
The code givhen below contains the common repository for our Application. 
  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3.    
  4. namespace RegistrationForm.Models  
  5. {  
  6.     public class RegRepository : IRegRepository  
  7.     {  
  8.         private RegContext _context;  
  9.    
  10.         public RegRepository(RegContext context)  
  11.         {  
  12.             _context = context;  
  13.         }  
  14.    
  15.         public IEnumerable<Registration> GetAllRegistrations()  
  16.         {  
  17.             return _context.Registrations.ToList();  
  18.         }  
  19.     }  
  20. }  
Server Side Validation
 
In the View Model, we implemented the default validations in the Registration page in our Applications.
  1. using System.ComponentModel.DataAnnotations;  
  2.    
  3. namespace RegistrationForm.ViewModels  
  4. {  
  5.     public class RegistrationViewModel  
  6.     {  
  7.         [Required]  
  8.         public string Name { getset; }  
  9.    
  10.         [Required]  
  11.         public string Location { getset; }  
  12.    
  13.         [Required]  
  14.         [RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$", ErrorMessage = "Not a valid Phone number")]  
  15.         public string Mobile { getset; }  
  16.    
  17.         [Required]  
  18.         [EmailAddress]  
  19.         public string Email { getset; }  
  20.    
  21.         [Required]  
  22.         [StringLength(5000, MinimumLength =10)]  
  23.         public string Address { getset; }  
  24.            
  25.     }  
  26. }  
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 list in home page with the help of common repository.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using RegistrationForm.Models;  
  3.    
  4. namespace RegistrationForm.Controllers.WebApp  
  5. {  
  6.     public class HomeController : Controller  
  7.     {  
  8.         private IRegRepository _repository;  
  9.    
  10.         public HomeController(IRegRepository repository)  
  11.         {  
  12.             _repository = repository;  
  13.         }  
  14.    
  15.         public IActionResult Home()  
  16.         {  
  17.             var data = _repository.GetAllRegistrations();  
  18.             return View(data);  
  19.         }  
  20.    
  21.     }  
  22. }  
Registration Controller
 
The registration controller contains the registration information in our Application.
  1. using Microsoft.AspNetCore.Mvc;  
  2. using Microsoft.Extensions.Logging;  
  3. using RegistrationForm.Models;  
  4. using RegistrationForm.ViewModels;  
  5. using System;  
  6.    
  7. namespace RegistrationForm.Controllers.WebApp  
  8. {  
  9.     public class RegistrationController : Controller  
  10.     {  
  11.         private RegContext _context;  
  12.         private ILogger<Registration> _logger;  
  13.    
  14.         public RegistrationController(RegContext context, ILogger<Registration> logger)  
  15.         {  
  16.             _context = context;  
  17.             _logger = logger;  
  18.         }  
  19.         public IActionResult Registration()  
  20.         {  
  21.             return View();  
  22.         }  
  23.         public IActionResult Home()  
  24.         {  
  25.             return View();  
  26.         }  
  27.         [HttpPost]  
  28.         public IActionResult Registration(RegistrationViewModel model)  
  29.         {  
  30.             ViewBag.SuccessMessage = null;  
  31.    
  32.             if (model.Email.Contains("menoth.com"))  
  33.             {  
  34.                 ModelState.AddModelError("Email""We don't support menoth Address !!");  
  35.             }  
  36.    
  37.             if (ModelState.IsValid)  
  38.             {  
  39.                 try  
  40.                 {  
  41.                     Registration regData = new Registration()  
  42.                     {  
  43.                         Id = Guid.NewGuid(),  
  44.                         Name = model.Name,  
  45.                         Email = model.Email,  
  46.                         Location = model.Location,  
  47.                         Mobile = model.Mobile,  
  48.                         Address = model.Address  
  49.                     };  
  50.    
  51.                     _context.Registrations.Add(regData);  
  52.                     _context.SaveChanges();  
  53.    
  54.                     ModelState.Clear();  
  55.                     ViewBag.SuccessMessage = "Registered Successfully !!";  
  56.                 }  
  57.                 catch (Exception ex)  
  58.                 {  
  59.                     _logger.LogError($" Registration Failure : {ex.Message} ");  
  60.                 }  
  61.             }  
  62.    
  63.             return View();  
  64.         }  
  65.     }  
  66. }  
Startup.cs
 
The class given blow contains the complete middleware details in our Applications.
  1. using System;  
  2. using Microsoft.AspNetCore.Builder;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Logging;  
  6. using RegistrationForm.Models;  
  7. using Microsoft.Extensions.Configuration;  
  8.    
  9. namespace RegistrationForm  
  10. {  
  11.     public class Startup  
  12.     {  
  13.         private IConfigurationRoot _config;  
  14.    
  15.         public Startup(IHostingEnvironment env)  
  16.         {  
  17.             var ConfigBuilder = new ConfigurationBuilder().SetBasePath(env.ContentRootPath)  
  18.             .AddJsonFile("appsettings.json");  
  19.             _config = ConfigBuilder.Build();  
  20.         }  
  21.         // This method gets called by the runtime. Use this method to add services to the container.  
  22.         // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940  
  23.         public void ConfigureServices(IServiceCollection services)  
  24.         {  
  25.             services.AddSingleton(_config);  
  26.             services.AddDbContext<RegContext>();  
  27.             services.AddScoped<IRegRepository, RegRepository>();  
  28.             services.AddTransient<RegContextSeedData>();  
  29.             services.AddMvc();  
  30.         }  
  31.    
  32.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  33.         public void Configure(IApplicationBuilder app, IHostingEnvironment env,  
  34.             ILoggerFactory loggerFactory, RegContextSeedData seeder)  
  35.         {  
  36.             loggerFactory.AddConsole();  
  37.    
  38.             if (env.IsDevelopment())  
  39.             {  
  40.                 app.UseDeveloperExceptionPage();  
  41.             }  
  42.             app.UseStaticFiles();  
  43.    
  44.             app.UseMvc(config =>  
  45.            {  
  46.                config.MapRoute(  
  47.                    name: "Default",  
  48.                    template: "{controller}/{action}/{id?}",  
  49.                    defaults: new { controller = "Home", action = "Home" }  
  50.                    );  
  51.            });  
  52.    
  53.             seeder.SeedData().Wait();  
  54.    
  55.         }  
  56.     }  
  57. }  
project.json
 
project.json contains the complete picture of dependency in our Applications.
  1. {  
  2.   "dependencies": {  
  3.     "Microsoft.AspNetCore.Diagnostics""1.0.0",  
  4.     "Microsoft.AspNetCore.Mvc""1.0.1",  
  5.     "Microsoft.AspNetCore.Mvc.TagHelpers""1.1.1",  
  6.     "Microsoft.AspNetCore.Mvc.ViewFeatures""1.1.1",  
  7.     "Microsoft.AspNetCore.Server.IISIntegration""1.0.0",  
  8.     "Microsoft.AspNetCore.Server.Kestrel""1.0.1",  
  9.     "Microsoft.AspNetCore.StaticFiles""1.1.0",  
  10.     "Microsoft.EntityFrameworkCore.SqlServer""1.0.1",  
  11.     "Microsoft.Extensions.Configuration.FileExtensions""1.0.0",  
  12.     "Microsoft.Extensions.Configuration.Json""1.0.0",  
  13.     "Microsoft.Extensions.Logging.Console""1.0.0",  
  14.     "Microsoft.EntityFrameworkCore.Design":"1.1.0",  
  15.     "Microsoft.NETCore.App": {  
  16.       "version""1.0.1",  
  17.       "type""platform"  
  18.     }  },  
  19.    
  20.   "tools": {  
  21.     "Microsoft.AspNetCore.Server.IISIntegration.Tools""1.0.0-preview2-final",  
  22.     "Microsoft.EntityFrameworkCore.Tools": {  
  23.       "version""1.0.0-preview2-final",  
  24.       "imports": [  
  25.         "portable-net45+win8+dnxcore50",  
  26.         "portable-net45+win8"  
  27.       ]  
  28.     }  
  29.   },  
  30.    
  31.      
  32.   "frameworks": {  
  33.     "netcoreapp1.0": {  
  34.       "imports": [  
  35.         "dotnet5.6",  
  36.         "portable-net45+win8"  
  37.       ]  
  38.     }  
  39.   },  
  40.    
  41.   "buildOptions": {  
  42.     "emitEntryPoint"true,  
  43.     "preserveCompilationContext"true  
  44.   },  
  45.    
  46.   "runtimeOptions": {  
  47.     "configProperties": {  
  48.       "System.GC.Server"true  
  49.     }  
  50.   },  
  51.    
  52.   "publishOptions": {  
  53.     "include": [  
  54.       "wwwroot",  
  55.       "web.config"  
  56.     ]  
  57.   },  
  58.    
  59.   "scripts": {  
  60.     "postpublish": [ "dotnet publish-iis --publish-folder %publish:OutputPath% --framework %publish:FullTargetFramework%" ]  
  61.   }  
  62. }  
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, fonts or even the image files.
  1. {  
  2.     "name""asp.net",  
  3.     "private"true,  
  4.   "dependencies": {  
  5.     "jquery""~3.1.1",  
  6.     "jquery-validation""~1.16.0",  
  7.     "jquery-validation-unobtrusive""~3.2.6",  
  8.     "bootstrap""~3.2.6"  
  9.        
  10.   }  
  11. }  
Code First Migration
 
First, we need to find the project location in CLI (Command Line Interface ) and afterwards, 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 my previous article by clicking here.
 
Project structure
 
The structure given below will be created after the ef migration in ASP.NET Core.
 
Picture Source : https://rajeeshmenoth.wordpress.com 
 
New Tag Helpers
 
We used latest ASP.NET Core Tag Helpers in Registration page to access controller and actions, validation etc.
  1. <div asp-validation-summary="All" class="text-danger"></div>  
  2.    
  3. <label asp-for="Name"></label>  
  4. <input asp-for="Name" class="form-control" />  
  5. <span asp-validation-for="Name" class="text-danger"></span>  
  6.    
  7. <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 in our Application. Now, create the default "_ViewImports.cshtml" file in View Folder and add the code given below in that file. 
  1. @addTagHelper "*,Microsoft.AspNetCore.Mvc.TagHelpers"  
Client Side validations
 
The Client Side validation is done through with the help of Bootstrap & jQuery etc. All these Client Side dependencies are accessed from bower.json file. 
 
 
Output
 

Reference
See Also
 
You can download other ASP.NET Core 1.0 source codes from MSDN Code, using the links, mentioned below.
Conclusion
 
We learnt 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. 

Up Next
    Ebook Download
    View all
    Learn
    View all