In this article, we are going to create a really simple application using ASP.NET Core MVC to get more familiar with this technology.
Introduction
Through this post, we are going to build a really simple application using the ASP.NET Core MVC technology. It is going to be pretty straightforward and this will allow us to have a brief overview of this tool. Here, we are going to use the second version of ASP.NET Core.
What is ASP.NET Core?
ASP.NET Core is an open-source software created by Microsoft. It allows us to develop web apps, services, IoT apps or mobile backends. The main difference with ASP.NET is ASP.NET Core is cross-platform. By the way, it lets us to run on .NET Core or .NET Framework.
What is MVC?
Firstly, let’s refresh our mind and let’s have a look at MVC. MVC, or Model-View-Controller, is a pattern that allows us to separate an application in three main components: Model, View, Controller. Now, we can debate over the question, “is MVC a design pattern or an architectural pattern?” but that’s another subject. Here, we have to retain the following information:
Model
The Model represents the data business logic layer. The Business Logic should be encapsulated in the model, along with any implementation logic for persisting the state of the application.
View
Views are responsible for presenting content through the user interface. There should be minimal logic within a View and this logic should be related to presenting content.
Controller
A Controller is a component that handles and responds to user input and interaction. It renders the appropriate View with the Model data as a response. So, it is responsible for selecting which Model type to work with and which View to render.
Creating our project
Let’s create our project, wherever we want, by doing the following commands:
dotnet new mvc -o gameapplicationcd gameapplication
<small>Creating our project and entering the folder</small>
We can also create our project inside Visual Studio (“New > Project > Visual C# > .NET Core > ASP.NET Core Web Application”, then select “Web Application (Model-View-Controller)”). This will generate a Solution and the project itself.
Project structure
Now that we created our application, let’s take a look at the structure of our folder.
Application folders
- Controllers — Controller classes
- Models — Model classes
- Views — HTML files for views
- wwwroot — static files like CSS files, icons or images
Configuration files
- Program.cs — contains the “Main()” method and it is used to initiate, build, run the server and host the application
- Startup.cs — used to configure middlewares on the request pipeline
- bundleconfig.json — used to store the project bundling and minification configuration for scripts and styles
First run
We can now run our project with the following command:
dotnet run
Running our project
We can also hit “F5”, or click the “play” button in Visual Studio and wait a few seconds.
Our project will be available at “http://localhost:RANDOM-PORT“.
Adding the Entity Framework Core
For our project, we are going to use the Entity Framework Core. Entity Framework Core is an object-relational mapper (ORM) that allows us to work with a database using .NET objects. It supports a development paradigm called Code First. It lets us create Model objects by writing simple classes (also known as POCO classes, from “plain-old CLR objects”). We can have the database created on the fly from our classes.
We can install the Entity Framework Core with the following command:
dotnet add package Microsoft.EntityFrameworkCore.SqlServerdotnet add package Microsoft.EntityFrameworkCore.Designdotnet add package Microsoft.EntityFrameworkCore.Tools
Installing the Entity Framework Core
We can also use the NuGet package manager through Visual Studio like so:
Install-Package Microsoft.EntityFrameworkCore.SqlServerInstall-Package Microsoft.EntityFrameworkCore.DesignInstall-Package Microsoft.EntityFrameworkCore.Tools
Installing the Entity Framework Core
Creating the Context
In our project, let’s create a folder named “Data”. In this folder, we can now create a file named “GameContext” and place the following code into that one:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using Microsoft.EntityFrameworkCore;using GameApplication._Models_;
namespace GameApplication.Data{ public class GameContext : DbContext { public GameContext(DbContextOptions<GameContext> options) : base(options) { }
public DbSet<Game> Games { get; set; } }}
Data/GameContext.cs file
Here we create only one “DbSet” property. A “DbSet” corresponds to a database table and an Entity corresponds to a row in the table.
Now, in our “Startup.cs” file, we have to add the following lines:
...using Microsoft.EntityFrameworkCore;...using GameApplication.Data;
public void ConfigureServices(IServiceCollection services){ services.AddDbContext<GameContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddMvc();}
Startup.cs file edited
Here, we register our context for Dependency Injection.
Using LocalDB
LocalDB is a lightweight version of the SQL Server Express Database Engine. LocalDB runs in a special execution mode of SQL Server Express that allows us to work with databases as “.mdf” files. LocalDB is installed by default with Visual Studio.
To use LocalDB, we have to change the connection string. So, in our “appsettings.json” file, we have to add the following things:
"ConnectionStrings": { "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=GameApplication;Trusted_Connection=True;MultipleActiveResultSets=true"}
appsettings.json file edited
Initializing Data
In our “Data” folder, let’s create a file named “DbInitializer” and fill it like so:
using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using GameApplication._Models_;
namespace GameApplication.Data{ public class DbInitializer { public static void Initialize(GameContext context) { if (context.Games.Any()) { return; }
var games = new List<Game> { new Game{Name="Super Mario Bros"}, new Game{Name="The Legend of Zelda"}, new Game{Name="Metroid"}, new Game{Name="Donkey Kong Country"} };
games.ForEach(g => context.Games.Add(g)); context.SaveChanges(); } }}
Data/DbInitializer.cs file
We now have to change the “Main()” method in the “Program.cs” file like so:
...using Microsoft.Extensions.DependencyInjection;...using GameApplication.Data;
public static void Main(string[] args){ var host = BuildWebHost(args);
using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services.GetRequiredService<GameContext>(); DbInitializer.Initialize(context); } catch (Exception ex) { var logger = services.GetRequiredService<ILogger<Program>>(); logger.LogError(ex, "An error occurred while seeding the database."); } }
host.Run();}
Program.cs filed edited
Migrations
In a real application, our data model will change frequently. So, for each change, we need to sync that database. We could configure the Entity Framework Core to automatically drop and re-create the database each time we change the data model. This is alright for development, but not for production because we would lose data. To solve this problem, we need to use the Code First Migrations feature.
Let’s create and execute a Migration like so:
dotnet ef migrations add InitialCreatedotnet ef database update// ORadd-migration InitialCreateupdate-database
Creation and running a Migration
We can use the Server Explorer to see that our migration has been run. Now, the first time we run the application, the database will be seeded with test data.
Creating our Controller
Now, we are going to create our “GamesController”. To achieve this, we are going to use the “scaffold” option, so we need Visual Studio and it is required that our project is embedded in a Solution. So, we can right click on the “Controllers” folder and select “ MVC controller with views, using Entity Framework”. Let’s name our Controller “Games”. For the Model class, we can select “Game” and for the Context “GameContext”. We can also choose to use shared view “_Layout.cshtml”. After a few seconds, we can see that a Controller with some code in it and a bunch of Views have been created for us.
It is time to run our application again. Let’s go to “http://localhost:RANDOM-PORT/games” to see the result. As we can see by looking at the result and the code, a lot has been made for us.
Conclusion
Through this article, we got an overview of the ASP.NET Core MVC Framework. We saw the basic concepts it uses. We built a small application using the MVCpattern and saw the different options that we have to create a dynamic web application. We saw how to create basic Models, Views and Controllers. We had a brief overview of the Entity Framework and how to use it. We are now ready to get further, because, of course, here, we didn’t talk about production environment or other elements.