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
- using System;
- using System.Collections.Generic;
-
- namespace ASP.NETCoreWithEFCore.Models
- {
- public class User
- {
- public int UserId { get; set; }
- public string Name { get; set; }
- public string Location { get; set; }
-
- public List<Role> Roles { get; set; }
- }
- }
Role.cs
- using System;
-
- namespace ASP.NETCoreWithEFCore.Models
- {
- public class Role
- {
- public int RoleId { get; set; }
- public RoleType RoleTyp { get; set; }
-
- public int UserId { get; set; }
- public User User { get; set; }
- }
-
- public enum RoleType
- {
- Admin,
- User
- }
- }
UserContext.cs
- using System;
- using Microsoft.EntityFrameworkCore;
-
- namespace ASP.NETCoreWithEFCore.Models
- {
- public class UserContext:DbContext
- {
- public UserContext(DbContextOptions<UserContext> dbcontextoption)
- :base(dbcontextoption)
- { }
-
- public DbSet<User> Users { get; set; }
- public DbSet<Role> Roles { get; set; }
- }
- }
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
- using Microsoft.AspNetCore.Builder;
- using Microsoft.AspNetCore.Hosting;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.DependencyInjection;
- using Microsoft.Extensions.Logging;
- using ASP.NETCoreWithEFCore.Models;
- using Microsoft.EntityFrameworkCore;
-
- namespace ASP.NETCoreWithEFCore
- {
- public class Startup
- {
- public Startup(IHostingEnvironment env)
- {
- var builder = new ConfigurationBuilder()
- .SetBasePath(env.ContentRootPath)
- .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
- .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
- .AddEnvironmentVariables();
-
- if (env.IsDevelopment())
- {
-
- builder.AddApplicationInsightsSettings(developerMode: true);
- }
- Configuration = builder.Build();
- }
-
- public IConfigurationRoot Configuration { get; }
-
-
- public void ConfigureServices(IServiceCollection services)
- {
-
- services.AddApplicationInsightsTelemetry(Configuration);
- services.AddMvc();
-
- var sqlconnection = @"Server=DESKTOP-2MS3DR5\SANLAB;Database=Lab;userid=username;password=password;";
- services.AddDbContext<UserContext>(dbcontextoption => dbcontextoption.UseSqlServer(sqlconnection));
- }
-
-
- public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
- {
- loggerFactory.AddConsole(Configuration.GetSection("Logging"));
- loggerFactory.AddDebug();
-
- app.UseApplicationInsightsRequestTelemetry();
-
- if (env.IsDevelopment())
- {
- app.UseDeveloperExceptionPage();
- app.UseBrowserLink();
- }
- else
- {
- app.UseExceptionHandler("/Home/Error");
- }
-
- app.UseApplicationInsightsExceptionTelemetry();
-
- app.UseStaticFiles();
-
- app.UseMvc(routes =>
- {
- routes.MapRoute(
- name: "default",
- template: "{controller=Home}/{action=Index}/{id?}");
- });
- }
- }
- }
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
- using Microsoft.AspNetCore.Mvc;
- using ASP.NETCoreWithEFCore.Models;
- using System.Linq;
-
-
- namespace ASP.NETCoreWithEFCore.Controllers
- {
- public class UserController : Controller
- {
- private UserContext usercontext;
-
- public UserController(UserContext context)
- {
- usercontext = context;
- }
-
-
-
- public IActionResult Index()
- {
- return View(usercontext.Users.ToList());
- }
-
- public IActionResult Create()
- {
- return View();
- }
-
- [HttpPost]
- [ValidateAntiForgeryToken]
- public IActionResult Create(User user)
- {
- if (ModelState.IsValid)
- {
- usercontext.Users.Add(user);
- usercontext.SaveChanges();
- return RedirectToAction("Index");
- }
- return View(user);
- }
- }
- }
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
- @model IEnumerable<ASP.NETCoreWithEFCore.Models.User>
-
- @{
- ViewBag.Title = "User Page";
- }
-
- <h2 class="panel-heading">User Dashboard</h2>
-
- <p>
- <a asp-controller="User" asp-action="Create">New User</a>
- </p>
-
- <table class="table table-responsive">
- <tr>
- <th>User Id</th>
- <th>Name</th>
- <th>Location</th>
- </tr>
- @foreach (var item in Model)
- {
- <tr>
- <td>
- @Html.DisplayFor(modelItem=> item.UserId)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Name)
- </td>
- <td>
- @Html.DisplayFor(modelItem => item.Location)
- </td>
- </tr>
- }
-
- </table>
Similarly, select an MVC View page and type the file name as Create and click Add button.
Create.cshtml
- @model ASP.NETCoreWithEFCore.Models.User
-
- @{
- ViewBag.Title = "New User";
- }
-
- <h2>@ViewData["Title"]</h2>
-
- <form asp-controller="User" asp-action="Create" method="post" class="form-horizontal" role="form">
- <div class="form-horizontal">
- <div asp-validation-summary="All" class="text-danger"></div>
- <div class="form-group">
- <label asp-for="Name" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Name" class="form-control" />
- <span asp-validation-for="Name" class="text-danger"></span>
- </div>
- </div>
- <div class="form-group">
- <label asp-for="Location" class="col-md-2 control-label"></label>
- <div class="col-md-10">
- <input asp-for="Location" class="form-control" />
- <span asp-validation-for="Location" class="text-danger"></span>
- </div>
- </div>
-
- <div class="form-group">
- <div class="col-md-offset-2 col-md-10">
- <input type="submit" value="Create" class="btn btn-default" />
- </div>
- </div>
- </div>
-
- </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.