There is not much difference between using the Entity Framework in a console application and ASP.NET MVC application. Now, we are going to build a simple application with a single screen as shown in the following image. In this screen, we will have a form where the user will enter the information about the employee; once the user submits the form, the information will be saved to the database and reflected in the following screenshots:
We can create a simple Model for the employee. We need to build a ViewModel for this View, as we need to get the employee information from the user and we need to show a list of employees as well on the same screen.
Let us create an ASP.NET Core application, adding the employee and showing the list of employees. The following is the step-by-step instructions to create the application for the previously mentioned objective:
NuGet
package.NuGet
package and
ef
EntityFramework commands (for database migration) as explained earlier in this chapter.config.json
to declare the connection string of the database:{ "Data": { "DefaultConnection": { "ConnectionString": "Data Source=MUGIL-PC\SQLEXPRESS;Initial Catalog=Validation;Integrated Security=True" } } }
project.json
to include EntityFramework 7 and EntityFramework commands. The changes are highlighted in bold:{ "version": "1.0.0-*", "compilationOptions":{ "emitEntryPoint": true }, "dependencies": { "Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final", "Microsoft.AspNet.Mvc": "6.0.0-rc1-final", "Microsoft.AspNet.Server.Kestrel": "1.0.0-rc1-final", "EntityFramework.MicrosoftSqlServer": "7.0.0-rc1-final", "EntityFramework.Commands": "7.0.0-rc1-final" }, "commands": { "web": "Microsoft.AspNet.Server.Kestrel", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules" ], "publishExclude": [ "**.user", "**.vspscc" ] }
Startup
class (Startup.cs
):config.json
fileConfigureServices
methodConfigure
method:using Microsoft.AspNet.Builder; using Microsoft.AspNet.Hosting; using Microsoft.AspNet.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Configuration; using Validation.Models; using Microsoft.Data.Entity; using Microsoft.Extensions.PlatformAbstractions; namespace Validation { public class Startup { public IConfigurationRoot Configuration { get; set; } public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { var builder = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.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.AddEntityFramework() .AddSqlServer() .AddDbContext<EmployeeDbContext>(options => { options.UseSqlServer(Configuration.Get<string> ("Data:DefaultConnection:ConnectionString")); }); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app) { app.UseIISPlatformHandler(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Employee}/ {action=Index}/{id?}"); }); } // Entry point for the application. public static void Main(string[] args) => WebApplication.Run<Startup>(args); } }
Models
and DbContext
classes.Models
folder and add the Employee
model class and EmployeeDbContext
class.Employee
Model class (Employee.cs
in the Models
folder):public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public string Designation { get; set; } public decimal Salary { get; set; } }
EmployeeDbContext
(EmployeeDbContext.cs
in the Models
folder):using Microsoft.Data.Entity; using Microsoft.Extensions.Configuration; namespace Validation.Models { public class EmployeeDbContext : DbContext { public IConfigurationRoot Configuration { get; set; } public DbSet<Employee> Employees { get; set; } public EmployeeDbContext() { var builder = new ConfigurationBuilder() .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = builder.Build(); } protected override void OnConfiguring (DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer (Configuration.Get<string> ("Data:DefaultConnection:ConnectionString")); base.OnConfiguring(optionsBuilder); } } }
ViewModels
:ViewModels
folder and add the EmployeeAddViewModel
:using MVCEF7.Models; namespace MVCEF7.ViewModels { public class EmployeeAddViewModel { public List<Employee> EmployeesList { get; set; } public Employee NewEmployee { get; set; } } }
ViewModel
has a couple of properties. EmployeesList
and NewEmployee
. EmployeesList
will contain the list of employees. This list would be fetched from the database. NewEmployee
will hold the employee information entered by the user.Controllers
to handle the incoming requests:Controllers
folder and add the EmployeeController
class with a couple of action methods-one for GET
and another for POST
. The Index
action method corresponding to the GET
action method will be called when you access the URL (http://localhost/Employee/Index
) or when you run the application. The POST Index
action method will be called when you submit the form as following:public IActionResult Index() { EmployeeAddViewModel employeeAddViewModel = new EmployeeAddViewModel(); using (var db = new EmployeeDbContext()) { employeeAddViewModel.EmployeesList = db.Employees.ToList(); employeeAddViewModel.NewEmployee = new Employee(); } return View(employeeAddViewModel); }
GET Index
action method, we are creating the ViewModel
object and passing it to the View.POST Index
action method:[HttpPost] public IActionResult Index(EmployeeAddViewModel employeeAddViewModel) { using (var db = new EmployeeDbContext()) { db.Employees.Add(employeeAddViewModel.NewEmployee); db.SaveChanges(); //Redirect to get Index GET method return RedirectToAction("Index"); } }
NewEmployee
property in the ViewModel, which contains the information on the user. Save it to the database. Once we save the employee information to the database and we redirect the control to the GET Index
action method, the GET Index
action method will again show the form to enter the employee information and the list of employees in table format.Views
folder:Views\_ViewStart.cshtml
with the following content:@{ Layout = "_Layout"; }
ViewsShared\_Layout.cshtml
with the following content:<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>@ViewBag.Title</title> </head> <body> <div> @RenderBody() </div> </body> </html>
ViewsEmployeeIndex.cshtml
with the following content:@model MVCEF.ViewModels.EmployeeAddViewModel @* //For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860 *@ @{ } <div> @using (Html.BeginForm("Index", "Employee", FormMethod.Post)) { <table> <tr> <td>@Html.LabelFor(Model => Model.NewEmployee.Name)</td> <td>@Html.TextBoxFor(Model => Model.NewEmployee.Name)</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.NewEmployee.Designation)</td> <td>@Html.TextBoxFor(Model => Model.NewEmployee.Designation)</td> </tr> <tr> <td>@Html.LabelFor(Model => Model.NewEmployee.Salary)</td> <td>@Html.TextBoxFor(Model => Model.NewEmployee.Salary)</td> </tr> <tr> <td colspan="2"><input type="submit" value="Submit"/> </td> </tr> </table> } </div> <br/><br/> <br/> <b> List of employees:</b> <br/> <div> <table border="1"> <tr> <th> ID </th> <th> Name </th> <th> Designation </th> <th> Salary </th> </tr> @foreach(var employee in Model.EmployeesList) { <tr> <td>@employee.EmployeeId</td> <td>@employee.Name</td> <td>@employee.Designation</td> <td>@employee.Salary</td> </tr> } </table> </div>
In the preceding Index
view, we create a form where we get the employee information from the user in the topmost div
. In the next div
, we show the list of employees in a tabular format.
Once we create all the folders and the files, the project structure should look like the following: