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 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 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 Applications.
- 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 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.
- {
- "ConnectionStrings": {
- "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=RegDB;Trusted_Connection=True;MultipleActiveResultSets=true"
- }
- }
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.
- 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 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 givhen below contains the common repository for our Application.
- using System.Collections.Generic;
- using System.Linq;
-
- namespace RegistrationForm.Models
- {
- public class RegRepository : IRegRepository
- {
- private RegContext _context;
-
- public RegRepository(RegContext context)
- {
- _context = context;
- }
-
- public IEnumerable<Registration> GetAllRegistrations()
- {
- return _context.Registrations.ToList();
- }
- }
- }
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 list in home page with the help of 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 blow 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();
- }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
- services.AddSingleton(_config);
- services.AddDbContext<RegContext>();
- services.AddScoped<IRegRepository, RegRepository>();
- services.AddTransient<RegContextSeedData>();
- services.AddMvc();
- }
-
-
- 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, fonts or even the 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 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.
- <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 in our Application. Now, create the default "_ViewImports.cshtml" file in 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 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.