paint-brush
Get Used to Building a .Net core MVC Application on Mac Visual Studioby@vdoomik
423 reads
423 reads

Get Used to Building a .Net core MVC Application on Mac Visual Studio

by Uladzislau BaryshchykDecember 17th, 2021
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this article I will demonstrate step by step how to create a.NET Core MVC project, connect the project to an AWS RDS database, use the. entity framework to. create a connection between the database and the application. I will not to use mapping and any pattterns such as repository pattern and unit of work because it is not connected with theme of article and out application will be compleatly coupled by. Entity Framework. The article is written on Mac OS and Visual Studio for Mac, as well as Visual Studio code.

Companies Mentioned

Mention Thumbnail
Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - Get Used to Building a .Net core MVC Application on Mac Visual Studio
Uladzislau Baryshchyk HackerNoon profile picture

Introduction

I want to use a Mac with Mac OS to develop my projects. Since I am a .NET developer, it is critically important for me to use windows based equipment. But since .NET core came out, I had the opportunity to use not only windows computers for development.


At first, I faced different problems, but gradually I solved them, and now I am doing development using Visual Studio Mac. In this article, I will demonstrate step by step how to create a .NET Core MVC project, connect the project to an AWS RDS database, use the entity framework to create a connection between the database and the application, and all I will do on Mac OS and use Visual Studio for Mac, as well as Visual Studio code.


In this article, I will not use mapping and any patterns such as repository pattern and unit of work because it is not connected with the theme of the article, and our application will be completely coupled by Entity Framework.

Let’s Get Started

First, we need to create a simple MVC project. To do this, open Visual Studio and create a new project (Image 1). Next, select .NET core 3.1 as Target Framework.


Image 1 - Let's get start


Next, it will be a surprise for you, but here we will see an empty window, just a white space. Do not worry, that is just closed by Solution Explorer by default. Go to View-Layout-Solution Explorer. Here, as in Visual Studio windows, in an MVC project, we have Models, Controllers, Views folders. That is what we need.

Next, we need to connect services for the operation of our application. Since we will use Entity Framework for communication with the database, we will need everything connected with it. An example of connected services is in Image 2.


Image 2 - NuGet Packages

Creating Model and Context

Let's create our model. It will be named for our application as Hospitals. Create a new class in the Model folder. Also, do not forget to connect data annotations. It will have the following code:


public class Hospital
{

    [Key]

    public int Hospitalid { get; set; }


    [StringLength(100)]

    [Display(Name = "Hospital name")]

    public string HospitalName { get; set; }


    [Required]

    [StringLength(100)]

    [Display(Name = "Dicision Maker")]

    public string Dicisionmaker { get; set; }


    [Required]

    [StringLength(100)]

    [Display(Name = "Email")]

    public string Email { get; set; }


    [Required]

    [StringLength(100)]

    [Display(Name = "Phone")]

    public string Phone { get; set; }
}


Next, let's create our context. Go to Solution Explorer, and then create a Data folder, and then an empty class. It should look like Image 3.


Image 3 - Creating class of DBContext


Further, to connect our application with the database, you need to add the following code to the DBContext class: Create class inherits from DbContext.


public class DBContext: DbContext


After that, add a link to our table in the database.


public DbSet <Hospital> Hospitals {get; set; }


Next, we will define the table with which there will be a connection when creating a model. A lot of o people do not use it, but I use it because, in my experience, I have had a lot of situations where the model class name is a different name in a database.


protected override void OnModelCreating (ModelBuilder modelBuilder)
 {
     modelBuilder.Entity <Hospital> () .ToTable ("Hospitals");
 }


So, then, create a constructor:


public DBContext(DbContextOptions<VegaDbContext> options):base(options)
        {
        }


Each .NET Core MVC project has a file appsettings.json in which you can configure the connection, and let's open this file (Image 4).


Image 4 - appsettings.json


Next, edit ConnectionStrings, but if is not created. Next the sample of connection string:


{
  "ConnectionStrings":{
    "Default":"Server=YOUR ENDPOINT ,1433; Database=DATABASENAME;
     Integrated Security=False;Persist Security Info=True;
     Trust Server Certificate = True;User ID=LOGIN;Password=PASSWORD"
  },


Then create a static method that will return a new context to us.


public static DBContext Create ()
{
    return new DBContext ();
}


As a result, you should get a similar code:


public class DBContext : DbContext

    {

        public DbSet<Hospital> Hospitals { get; set; }


        protected override void OnModelCreating(ModelBuilder modelBuilder)

        {

            modelBuilder.Entity<Hospital>().ToTable("Hospitals");

        }


        


      public DBContext(DbContextOptions<VegaDbContext> options):base(options)
        {
        }


        public static DBContext Create()

        {

            return new DBContext();

        }


    }


For this step, we are done.

Create a Controller

We are now ready to create our controller. Next, we need to create three methods: show all records from the table, add a new record to the table and create an empty page to populate the model. I do not show it anymore since the purpose of this article is to show the very principle of operation.


Let's create a new control and name itHospitalsController (Image 5).


Image 5 - Creating a HospitalsController

Next, Let us inherit our class the Controller class by using code:


public class HospitalsController:Controller


Next, create a database connection in the controller.


private DBContext _context;


And add code:


public HospitalsController()

{

    _context = new DBContext();

}


protected override void Dispose(bool disposing) => _context.Dispose();


Next, for basic operations, let's create three methods. The first one will display the list of entities. In this code, we read the values from the database and return them to the view, which we will create later (Index, Save, New). Do not forget to use routing. Add the following code:


[Route("Hospitals/Index")]

        public ActionResult Index()

        {

            var CustomersList = _context.Hospitals;

            return View("Index", HospitalsList);

        }


The next, create the second method will create a new entity. Add the following code:


public ActionResult New()

        {

            var hospital = new Hospital();

             return View("HospitalsForm", hospital);

        }


Next, create the third that will save a new entity. Let's add the following code:


public ActionResult Save(Hospital hospital)

        {

            if (!ModelState.IsValid)

            {

                var _hospital = hospital;                


                return View("CustomerForm", hospital);

            }


            _context.Hospitals.Add(hospital);


            _context.SaveChanges();


            return RedirectToAction("Index", "Hospitals");

        }


For this step, we are done.

Create Views


Finally, we have to do is add the views to our application.

Next, let's edit _Layout in the Shared folder.


<li class = "nav-item">
 <a class="nav-link text-dark" asp-area="" asp-controller="Hospitals" asp-action="Index"> Hospitals </a>
</li>


Next, for our example, we do with two. Views Visual Studio on Mac does not have standard functionality without connecting various extensions to immediately create a View from a controller (Image 6).


Image 6 - Creating the view


To create this, go to the View tab and create a new folder that has Hospitals. Next, create two view files - Index-for list of hospitals and HospitalsForm - for creating a hospital. It will display us a list, and there will be a button with the creation of a new one.

Add the following code to Index:


@model IEnumerable<My_Code_first.Models.Hospital>

@{ ViewBag.Title = "Hospitals";

                Layout = "~/Views/Shared/_Layout.cshtml"; }

<h2>Customers</h2>

<p>
    @Html.ActionLink("New Hospital", "New", "Hospitals", null, new { @class = "btn btn-primary" })
</p>
<table class="table">

    <tr>
        <th>
            Hospital ID
        </th>
        <th> Hospital Name</th>
        <th> Dicisionmaker</th>
        <th> Phone</th>
        <th> Email</th>
        @foreach (var hospital in Model)
        {

    <tr>

        <td>
            @Html.DisplayFor(hospitalId => hospital.Hospitalid)
        </td>

        <td>
            @Html.DisplayFor(hospitalName => hospital.HospitalName)
        </td>

        <td>
            @Html.DisplayFor(hospitalDicisionmaker => hospital.Dicisionmaker)
        </td>

        <td>
            @Html.DisplayFor(hospitalPhone => hospital.Phone)
       </td>

        <td>
            @Html.DisplayFor(hospitalEmail => hospital.Email)
        </td>
    </tr>}
    </table>


Next, add the code is in HospitalForm:


@model My_Code_first.Models.Hospital

@using (Html.BeginForm("Save", "Hospitals"))

{

    @Html.ValidationSummary()

    <div class="form-group">

        @Html.LabelFor(m => m.HospitalName)

        @Html.TextBoxFor(m => m.HospitalName, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.HospitalName)


    </div>


    <div class="form-group">

        @Html.LabelFor(m => m.Dicisionmaker)

        @Html.TextBoxFor(m => m.Dicisionmaker, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Dicisionmaker)


    </div>


    <div class="form-group">

        @Html.LabelFor(m => m.Email)

        @Html.TextBoxFor(m => m.Email, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Email)


    </div>

    <div class="form-group">

        @Html.LabelFor(m => m.Phone)

        @Html.TextBoxFor(m => m.Phone, new { @class = "form-control" })

        @Html.ValidationMessageFor(m => m.Phone)


    </div>


    <button type="submit" class="btn btn-primary"> Save </button>

    @Html.HiddenFor(m => m.Hospitalid)

    @Html.AntiForgeryToken()


}


For this step of creating a view, we are done.

Connect the Database

You can argue for a long time how to choose a database for work. However, to reduce the load on our working machine and not install various applications for working with a database, I will create a new database based on an instance in my Amazon account. I have already shown how to create a new database in Amazon in one of my articles. It is a very similar step.


Immediately, we need an application that can communicate with the database on Amazon, and the best option is VS Code. Open it and go to the Extensions section. There, we put on the SQLTools and install it (Image 7).


Image 7 - SQLTools


Next, we need to connect to our database on Amazon. Find the Endpoint of RDS instance and copy it (Image 8).


Image 8 - AWS RDS Endpoint


Next, create a new connection, and select in Server Address Endpoint and rdsadmin as a database, as well as a username and password (Image 9).


Image 9 - Connection Assistant


Although the entity framework allows you to create a database; I prefer to create a database manually. Next, to do this, run a query.


CREATE DATABASE hospitalServises


After that, let's go back and change our database connection (Image 10).


Image 10 - Database test connection


For this step, we are done.

Connect Entity Framework for Our Application

Since we are using the CodeFirst approach, we need to use the migrations. In Visual Studio mac, we do not have a Package Manager console, and we can use the terminal to create the migration.


For the test, let us open the project folder in the terminal and run the command you can see on Image 11.


dotnet ef

Image 11 - Test of EF


Next, I want to note that it is necessary to open exactly the folder with which Startup.cs is located; otherwise, the creation of the migration will not work. To create our migration, enter the command (Image 12):


dotnet ef migrations add InitialUpdate

Image 12 - Creating migration


Next, update the database using the command (Image 13).


dotnet ef database update

Image 13 - Updating the database


After successful completion of the database update, let's check the creation of tables. Open VS Code and open the database.


As we can see, our table is created. For this step, we are done.

Test Application


Next for the test, launch our application and go to Hospitals (Image 14).


Image 14 - Hospitals View

Then, create a new hospital (Image 15):

Image 15 - Creating a new hospital

Then we'll save. As you can see, everything works (Image 16).

Image 13 - The new hospital has been created

Conclusion

In conclusion, we created a new .NET MVC application, created a model, a controller, and a view. In addition, we prepared a context for creating a connection to the database. Also, we created a connection to the database, edited connection strings, and created a connection in our .NET MVC application with Entity Framework, which is not a difficult process if you follow all the suggested steps.