Getting Started With ASP.NET Core, EF Core Using SQL Server On Windows

In this article, we will discuss how we can develop the User Management application, using ASP.Net Core with Entity Framework Core in Windows.

In this article, we will discuss how we can develop the User Management application, using ASP.NET Core with Entity Framework Core in Windows. We have already discussed about ASP.NET Core with "hello world" application on Windows in my previous articles. If you want to learn ASP.NET Core and its features, visit the following links.

In this article, we will discuss the following.

  • Prerequisite
  • Create an ASP.NET Core Web Application on Windows
  • How to install the Entity Framework Core
  • How to add Entity Framework Core package to project.json file
  • Create a model class
  • How to register your context with dependency injection
  • How to create our database
  • How to create our controller
  • How to create view
  • How to run the user management application

Prerequisite

  • Visual Studio 2015
  • .NET Core 1.0

You need to download and install the free community edition of Visual Studio 2015. You can download it from here-  Visual Studio. Furthermore, you can download .NET Core 1.0 for Windows platform from .NET website.

Create an ASP.NET Core Web Application on Windows

Open Visual Studio 2015.

Go to File menu, point to new, and click new project.
A "New Project" window will open. You can select an installed template like “.NET Core” in Visual C# Template and then select the ASP.NET Core Web Application (.NET Core).
Type the project name as ASP.NETCoreWithEFCore. Choose the project location path and click OK button.
 
You can select a template “Web Application” and click OK button.
 
 
 
Now, you can see ASP.NETCoreWithEFCore project structure, as shown in the screen shot, given below.
 
 

How to install the Entity Framework Core

We are going to use EF Core and install the package for the database provider from NuGet Package Manager Console in Visual Studio 2015. We will see how to install EF Core for SQL Server database using the command, in the below steps.

  • Go to Visual Studio Tools, point to NuGet Package Manager, and then click Package Manager Console menu.
  • After some time, Package Console Manager gets ready successfully.
  • Type Install-Package Microsoft.EntityFrameworkCore.SqlServer and Enter.
  • After sometime, the Microsoft.EntityFrameworkCore.Sqlserver 1.0.1 will be installed successfully.
  • Then, we have to wait for some time to restore the packages.
  
  • Type Install-Package Microsoft.EntityFrameworkCore.Tools –Pre and Enter.
  • After sometime, the Microsoft.EntityFrameworkCore.Tool 1.0.0-preview2-final installs successfully. Then, we have to wait some time for restoring the packages.
 

How to add Entity Framework Core package to project.json file

Now, you can see in detail how to configure the Entity Framework Core package in project.json file. 

  • Go to Solution Explorer and then open project.json file.
  • Now, verify the tools section whether the EF Core package is configured or not. 
  • Now, add the “Microsoft.EntityFrameworkCore.Tools : 1.0.0-preview2-final”.
  

Create a model class

We have to create a models folder in project. After that, you can add the model class and context class under the models folder, as in the below given steps.

Go to the Models folder.

Right click the Models folder and point to Add followed by clicking the Class.
 
Select a class and give the class name as UserContext,and click Add button.

Similarly, you can add User and Role classes under the Models folder in project.

User.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3.   
  4. namespace ASP.NETCoreWithEFCore.Models  
  5. {  
  6.     public class User  
  7.     {  
  8.         public int UserId { get; set; }  
  9.         public string Name { get; set; }  
  10.         public string Location { get; set; }  
  11.   
  12.         public List<Role> Roles { get; set; }  
  13.     }  
  14. }  

Role.cs

  1. using System;  
  2.   
  3. namespace ASP.NETCoreWithEFCore.Models  
  4. {  
  5.     public class Role  
  6.     {  
  7.         public int RoleId { get; set; }  
  8.         public RoleType RoleTyp { get; set; }  
  9.   
  10.         public int UserId { get; set; }  
  11.         public User User { get; set; }  
  12.     }  
  13.   
  14.     public enum RoleType  
  15.     {  
  16.         Admin,  
  17.         User  
  18.     }  
  19. }  

UserContext.cs

  1. using System;  
  2. using Microsoft.EntityFrameworkCore;  
  3.   
  4. namespace ASP.NETCoreWithEFCore.Models  
  5. {  
  6.     public class UserContext:DbContext  
  7.     {  
  8.         public UserContext(DbContextOptions<UserContext> dbcontextoption)  
  9.             :base(dbcontextoption)  
  10.         { }  
  11.   
  12.         public DbSet<User> Users { get; set; }  
  13.         public DbSet<Role> Roles { get; set; }  
  14.     }  
  15. }  

How to register our context class with dependency injection

You can see, in detail, how to register your context class with dependency injection running application startup in the startup class.

  • Go to Solution Explorer, open Startup.cs class, and add the following namespaces and register context class.

Startup.cs

  1. using Microsoft.AspNetCore.Builder;  
  2. using Microsoft.AspNetCore.Hosting;  
  3. using Microsoft.Extensions.Configuration;  
  4. using Microsoft.Extensions.DependencyInjection;  
  5. using Microsoft.Extensions.Logging;  
  6. using ASP.NETCoreWithEFCore.Models;  
  7. using Microsoft.EntityFrameworkCore;  
  8.   
  9. namespace ASP.NETCoreWithEFCore  
  10. {  
  11.     public class Startup  
  12.     {  
  13.         public Startup(IHostingEnvironment env)  
  14.         {  
  15.             var builder = new ConfigurationBuilder()  
  16.                 .SetBasePath(env.ContentRootPath)  
  17.                 .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)  
  18.                 .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)  
  19.                 .AddEnvironmentVariables();  
  20.   
  21.             if (env.IsDevelopment())  
  22.             {  
  23.                 // This will push telemetry data through Application Insights pipeline faster, allowing you to view results immediately.  
  24.                 builder.AddApplicationInsightsSettings(developerMode: true);  
  25.             }  
  26.             Configuration = builder.Build();  
  27.         }  
  28.   
  29.         public IConfigurationRoot Configuration { get; }  
  30.   
  31.         // This method gets called by the runtime. Use this method to add services to the container.  
  32.         public void ConfigureServices(IServiceCollection services)  
  33.         {  
  34.             // Add framework services.  
  35.             services.AddApplicationInsightsTelemetry(Configuration);  
  36.             services.AddMvc();  
  37.   
  38.             var sqlconnection = @"Server=DESKTOP-2MS3DR5\SANLAB;Database=Lab;userid=username;password=password;";  
  39.             services.AddDbContext<UserContext>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection));  
  40.         }  
  41.   
  42.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  43.         public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)  
  44.         {  
  45.             loggerFactory.AddConsole(Configuration.GetSection("Logging"));  
  46.             loggerFactory.AddDebug();  
  47.   
  48.             app.UseApplicationInsightsRequestTelemetry();  
  49.   
  50.             if (env.IsDevelopment())  
  51.             {  
  52.                 app.UseDeveloperExceptionPage();  
  53.                 app.UseBrowserLink();  
  54.             }  
  55.             else  
  56.             {  
  57.                 app.UseExceptionHandler("/Home/Error");  
  58.             }  
  59.   
  60.             app.UseApplicationInsightsExceptionTelemetry();  
  61.   
  62.             app.UseStaticFiles();  
  63.   
  64.             app.UseMvc(routes =>  
  65.             {  
  66.                 routes.MapRoute(  
  67.                     name: "default",  
  68.                     template"{controller=Home}/{action=Index}/{id?}");  
  69.             });  
  70.         }  
  71.     }  
  72. }  

How to create our database

Now, we are going to create our database and tables for our models.

  • Go to Visual Studio Tools, point to NuGet Package Manager, and  click Package Manager Console menu.
  • After some time, the Package Console Manager is ready.
  • Type Add-Migration MyFirstMigration and press Enter.
 

If you have received error like “the term ‘Add-Migration’ is not recognized as the name of a cmdlet, then close and reopen the Visual Studio. 

  • Type Update-Database and press Enter.
 

How to create our Controller

Go to the Controllers folder.

Right click on it and point to Add followed by clicking the New Item.
 
Select an MVC Controller class and type the class name as UserController and click Add button.

UserController.cs

  1. using Microsoft.AspNetCore.Mvc;  
  2. using ASP.NETCoreWithEFCore.Models;  
  3. using System.Linq;  
  4. // For more information on enabling MVC for empty projects, visit http://go.microsoft.com/fwlink/?LinkID=397860  
  5.   
  6. namespace ASP.NETCoreWithEFCore.Controllers  
  7. {  
  8.     public class UserController : Controller  
  9.     {  
  10.         private UserContext usercontext;  
  11.   
  12.         public UserController(UserContext context)  
  13.         {  
  14.             usercontext = context;  
  15.         }  
  16.           
  17.   
  18.         // GET: /<controller>/  
  19.         public IActionResult Index()  
  20.         {  
  21.             return View(usercontext.Users.ToList());  
  22.         }  
  23.   
  24.         public IActionResult Create()  
  25.         {  
  26.             return View();  
  27.         }  
  28.   
  29.         [HttpPost]  
  30.         [ValidateAntiForgeryToken]  
  31.         public IActionResult Create(User user)  
  32.         {  
  33.             if (ModelState.IsValid)  
  34.             {  
  35.                 usercontext.Users.Add(user);  
  36.                 usercontext.SaveChanges();  
  37.                 return RedirectToAction("Index");  
  38.             }  
  39.             return View(user);  
  40.         }  
  41.     }  
  42. }  

How to create View

We have to create a User folder in Views folder. After that, you can add the view page under the views folder, with the given steps.

Right click the User folder and point to "Add" followed by clicking the "New Item".

Select an MVC View page and type file name as Index and click Add button.

Index.cshtml

  1. @model IEnumerable<ASP.NETCoreWithEFCore.Models.User>  
  2.   
  3. @{  
  4.     ViewBag.Title = "User Page";  
  5. }  
  6.   
  7. <h2 class="panel-heading">User Dashboard</h2>  
  8.   
  9. <p>  
  10.     <a asp-controller="User" asp-action="Create">New User</a>  
  11. </p>  
  12.   
  13. <table class="table table-responsive">  
  14.     <tr>   
  15.         <th>User Id</th>  
  16.         <th>Name</th>  
  17.         <th>Location</th>  
  18.     </tr>  
  19.     @foreach (var item in Model)  
  20.     {  
  21.         <tr>  
  22.             <td>  
  23.                @Html.DisplayFor(modelItem=> item.UserId)  
  24.             </td>  
  25.             <td>  
  26.                 @Html.DisplayFor(modelItem => item.Name)  
  27.             </td>  
  28.             <td>  
  29.                 @Html.DisplayFor(modelItem => item.Location)  
  30.             </td>  
  31.         </tr>  
  32.     }  
  33.       
  34. </table>  

Similarly, select an MVC View page and type the file name as Create and click Add button.

Create.cshtml

  1. @model ASP.NETCoreWithEFCore.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "New User";  
  5. }  
  6.   
  7. <h2>@ViewData["Title"]</h2>  
  8.   
  9. <form asp-controller="User" asp-action="Create" method="post" class="form-horizontal" role="form">  
  10.     <div class="form-horizontal">  
  11.         <div asp-validation-summary="All" class="text-danger"></div>  
  12.         <div class="form-group">  
  13.             <label asp-for="Name" class="col-md-2 control-label"></label>  
  14.             <div class="col-md-10">  
  15.                 <input asp-for="Name" class="form-control" />  
  16.                 <span asp-validation-for="Name" class="text-danger"></span>  
  17.             </div>  
  18.         </div>  
  19.         <div class="form-group">  
  20.         <label asp-for="Location" class="col-md-2 control-label"></label>  
  21.         <div class="col-md-10">  
  22.             <input asp-for="Location" class="form-control" />  
  23.             <span asp-validation-for="Location" class="text-danger"></span>  
  24.         </div>  
  25.     </div>  
  26.            
  27.     <div class="form-group">  
  28.         <div class="col-md-offset-2 col-md-10">  
  29.             <input type="submit" value="Create" class="btn btn-default" />  
  30.         </div>  
  31.     </div>  
  32.  </div>  
  33.   
  34. </form>   

How to Run the User Management application

You can now run the User Management application and it will be built and open in the browser.

 
 
 
Source Code

You can download the free source code from here

Reference

Conclusion

I hope you understood developing the ASP.NET Core Web application using EF Core on Windows and running it. I have covered all the required things. If you find anything missing in this article, please let me know. Please share your valuable feedback or suggestions.