Create an MVC Web App in .NET Core
Configure an Entity Framework to persist data
This post we will generate an MVC Web App using .Net Core. To learn how to create a base project in .Net Core and understand its configuration in a more precise way you can read the previous post.
.NET Core framework already provides scaffolding tools for bootstrapping your projects, and in this post we will use them to create a new MVC project and we will use
Entity Framework for to create and manage a database, using
code first approach for its design.
For our initial setup we just need to run:
dotnet new mvc -o test-net-core-mvc
This command will create a basic MVC application, where
test-net-core-mvc will be our project’s name, and it will have the following structure:
Let’s analyze the structure a bit:
Here we have the typical .NET MVC architecture. In our
Controllers directory, we have one default
HomeController which looks like this:
For this example we use annotations for routes, but you can also define them in the
Views directory we have, for each
Controller, a directory where its name and a view for each controller method. Also, there is a folder where the shared views are located called
The only part missing are the
Models, which require one more directory, where the items related to the database and the views will be located. These are called
Another important folder is
wwwroot, where we will have our public files, css, images, js files, etc.
Then we will install our project’s dependencies and run our application for which we will run the following commands:
With this we will be able to test our project at localhost:5000.
Entity Framework with Postgres
The only thing missing now would be our models for which we will use the ORM provided by the Entity Framework.
In order to map our models to a
postgres database using the Entity Framework ORM, we are going to add the following references to our
Then we will create the directory
Models/DataBase and in this path, we will create a file called
DataBaseContext.cs with the following content:
DataBaseContext.cs file is what we use for mapping our models with the database. In the next example, we are adding a
Then in the same directory we will add two more files:
BaseEntity.cs, as follows:
This class is going to be used to put common attributes to all models.
User.cs, which is maps to a table, with the following content:
Now, we must add the services configuration in the
Startup.cs to indicate that we will use the
Entity Framework, and in this particular case,
Postgres as a database.
The following line is placed below the
And add this references:
Finally, we need to specify the connection to the database from the
appSettings.json by adding this hash:
Now, to create database and the database migration we must run the following commands:
dotnet ef migrations add InitialMigration
dotnet ef database update
You have configured your web application .Net Core using Entity Framework for the connection to the database.