Using the Entity Framework in ASP.NET MVC applications

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:

Using the Entity Framework in ASP.NET MVC applications

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:

  1. Create an ASP.NET Core project in Visual Studio by selecting an empty ASP.NET 5 application.
  2. Install the ASP.NET Core NuGet package.
  3. Install the Entity Framework 7 NuGet package and ef EntityFramework commands (for database migration) as explained earlier in this chapter.
  4. Add config.json to declare the connection string of the database:
    { 
      "Data": { 
        "DefaultConnection": { 
          "ConnectionString": "Data Source=MUGIL-PC\SQLEXPRESS;Initial Catalog=Validation;Integrated Security=True" 
        } 
      } 
    } 
    
  5. Update 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" 
      ] 
    } 
    
  6. Configure MVC in the Startup class (Startup.cs):
    • In the constructor, we are building the configuration by reading the config.json file
    • Add the MVC service and the Entity Framework service to the services in the ConfigureServices method
    • Configure the MVC routing in the Configure 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);
       }
       }
  7. Create Models and DbContext classes.
  8. Create the Models folder and add the Employee model class and EmployeeDbContext class.
  9. Create the 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; } 
    } 
    
  10. Create 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); 
        } 
      } 
    } 
    
  11. Create ViewModels:
    • As we are going to show a list of employees and the form to add employees in the same screen, we are going to build a Model specific to this View. This model will contain information about the list of employees and the employee to be added.
  12. Create the 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; } 
      } 
    } 
    
    • This 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.
  13. Create Controllers to handle the incoming requests:
    • Create a 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); 
      } 
      
    • In the preceding GET Index action method, we are creating the ViewModel object and passing it to the View.
    • The following code uses 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"); 
        } 
       
      } 
      
    • We get the 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.
  14. Add the Views folder:
    1. Create Views\_ViewStart.cshtml with the following content:
      @{ 
        Layout = "_Layout"; 
      } 
      
    2. Create 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> 
      
    3. Create 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:

Using the Entity Framework in ASP.NET MVC applications

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset