Lesson 6 - Scaffolding and Entity Framework in ASP.NET Core MVC

C# .NET ASP.NET ASP.NET Core ASP.NET Core MVC Basics Scaffolding and Entity Framework in ASP.NET Core MVC

In the previous lesson, Modifying the MVC template in ASP.NET Core, we've modified a template project from Visual Studio into a personal blog. Today's C# .NET tutorial is packed with the most modern technologies to help us create an article editor in a moment.

Scaffolding

Scaffolding in ASP.NET Core MVC

Web frameworks are designed to simplify the programmer's work as much as possible, and in particular, reduce the amount of code they need to write. Although they are doing well, there are still situations where a certain amount of stereotypical code is necessary and there's no way the framework could change this.

We are going to program website article administration, so we'll need a controller, article model, database table and 5 views (index, edit, create, delete, detail). The app simply has to contain these components no matter how brilliant language we are programming in. However, they don't have to be stereotypically written by the programmer, but the IDE can generate them for us. This principle is called scaffolding. Visual Studio simply pre-generates a database, controller, and views. So we get the skeleton with the basic functionality which we can only modify.

Entity framework

We'll work with the database using the Entity Framework Core technology, it's the ORM approach (object-relational mapping). The database tables are mapped directly to C# classes, we work only with objects in our code and the framework itself generates SQL queries in the background. We won't get in contact with the MS-SQL language at all and our application is 100% object-oriented. Although I will try to describe everything in detail, I recommend the newcomers in ORM to visit the Databases in C# .NET section where ORM is described in detail.

Code First and Database First approaches

There are two approaches to work with Entity Framework. We can create a C# class and based on it, EF will automatically generate the database table and the necessary context. This approach is called Code First. The second way is to create a database from which EF generates classes and the context. It's probably not surprising that the second approach is called Database First. Since creating a class is much easier than creating a database, I have chosen the Code-First approach for the tutorial.

Creating the model

Entity Framework uses certain conventions and pluralizes class names. Let's add a new Article class to the Models folder. It'll look like this:

public class Article
{
    public int Id { get; set; }
    public string Content { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
}

The class contains several properties, namely:

  • Id
  • Content
  • Title
  • Description

You can add e.g. the publication date to the article and others. Every entity must have an Id. Once we generate tables from the code, it'll become its primary key, which will uniquely identify the articles even some had the same title.

Rebuild

So that Entity Framework is able to generate the database, we need to rebuild the project first. It's because it hasn't yet been built with this class. We can do this by right-clicking on the project in Solution Explorer and choosing Rebuild. This is how the class is compiled.

Rebuilding a project in ASP.NET Core MVC

Now we'll add a new controller to the Controllers folder. A dialog with the scaffolding selection pops up and we choose MVC Controller with views, using Entity Framework.

Scaffolding a controller in ASP.NET Core MVC

As the model, we'll choose our Article class and, as the data context, we'll select the already existing application context in which the users and their roles are. We'll keep the default ArticlesController name. Note that we can also specify whether we want to use the layout and a few other things.

Scaffolded controler in ASP.NET Core MVC

We confirm the dialog.

We've generated ArticlesController with several methods (actions). We can find the following actions there:

  • Index() - Listing of all the articles
  • Details() - Details of one article
  • Create() - Creating an article
  • Edit() - Editing an article
  • Delete() - Deleting an article

When we look into the Views folder, we'll find the Articles folder and 5 views for these actions in it.

Let's run the application and go to the Articles tab. The project now either displays an error message or works, depending on the version of the tools.

Article list in ASP.NET Core MVC

Migration

If the Articles page displays an error for you, the database migration hasn't been executed. In our case, this means that we have created the Article class, but there's no corresponding table in the database yet. To make our database correspond to our models, we need to migrate it. In Visual Studio, select Tools -> NuGet Package Manager -> Package Manager Console from the top menu. The console opens at the bottom of the window. Enter the following command there:

Add-Migration Article_Create

Article_Create is the name of our migration, you can enter any other name. Confirm with the Enter key. It'll take a while to start.

As soon as the migrations are created, we have to run them on the database. This is done by the command:

Update-Database

Whenever we create a new database model, remove it or change it (for example, add a property to it, delete a property, etc.), we'll do the same procedure as we've just described. VS updates our database and Entity Framework context for us so that all the changes are reflected in it.

If your app didn't work, run it now again and go to the Articles link. We can see that the article administration has been generated automatically and is fully functional. We can try to add a test article:

Adding a new article in ASP.NET Core MVC

You'll see it in the article list:

An article list in ASP.NET Core MVC

And we can also open it using the Details link:

An article detail in ASP.NET Core MVC

Note the URL address:

http://localhost:44311/Articles/Details/1

The first parameter specifies the name of the controller to call (ArticlesController), the second is the name of its method (Details()). In previous applications, we had only one method in our controller (Index()) and it was called automatically when no parameter were entered. Other parameters in the address are the parameters of the given controller's action (method), here it's the Id of the article that we are displaying.

We've already explained this mechanism, which converts the URL address to controller method calls (routing), in the previous lessons. Just to remind you, I'll add that we can change its settings in Startup.cs.

The Details() method in ArticlesController looks like this:

// GET: Articles/Details/5
public async Task<IActionResult> Details(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var article = await _context.Article
        .SingleOrDefaultAsync(m => m.Id == id);
    if (article == null)
    {
        return NotFound();
    }

    return View(article);
}

The nullable id parameter is written as an ordinary method parameter. It's really just this single line which is responsible for getting an article from the database:

var article = await _context.Article.SingleOrDefaultAsync(m => m.Id == id);

If you didn't know Entity Framework, you're probably going to love it now :)

The database is stored in a local file, not in the project folder, but in your user folder in C:\Users\<your name>. You can look into it, the database file has the .mdf extension. This also means that if something goes wrong and you want to download the working solution under the article today or next time, the database will not exist in it and the project will not work. After downloading the project, you must call Add-Migration Migration_Name and Update-Database in the Package Manager Console to create an empty database for your project. only after that, the downloaded project will work.

Try reading the source code of today's solution and repeat how everything works. In the next lesson, Article administration and editor in ASP.NET Core MVC, we'll begin to modify the scaffolded code so that the articles get closer to our vision. As always, you can download the project below.


 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Activities (2)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!