Section 2: ASP .Net MVC Model


Section 2: ASP .Net Model

Introuduction:

In the previous section 1, you have seen how we created the APS .Net Core project. In this section let us see how to create a Database in ASP .Net using Entity Framework.

Data Entity Models:

Models in ASP .Net are a POCO (Plain Old CLR Objects) "class", which means that they are not dependent on any framework (such as Entity Framework).

Models represent the data(Entity) to be stored in the database. For instance, if I create a class - "Student" with the name and registration ID as its members, then we will be creating a table in our Database named "Student" and name and registration ID as its columns. This is called Entity in Entity Framework.

Hence, in this section, we will first write the Model(Entity) class, and the Entity Framework will create the Table for the Model in the database.

Again, to be more clearer on the concepts of Models, here is a simpler example. 

When we create a class as below:

class test
{
    public int a;
    public string b;
}

This will create a table "test" with columns a and b.

Let us start by creating a Model for our previously created project:

To add a model class, add a folder called Models(this is just for grouping files) and add a class Hotel.cs. 


The properties in the class will represent the columns in the DB table.The [Key] attribute says that this column is a primary key; [Required] attributes say that the property is mandatory. These attributes are called Data Annotations in the Entity Framework, and it is defined in System.ComponentModel.DataAnnotations. The relations between the Entities can be created using the Data Annotations.


There is another method to configure the Entities in EF and that is called Fluent API. However, I am not covering that in this course.

 

       public class Hotel
      {
        [Key]
        public int Id { get; set; }
        [Required]
        public string Name { get; set; }
        [Required]
        public string Province { get; set; }
        public DateTime Created { get; set; }
        public byte[] Image { get; set; }
        public DateTime Established { get; set; }
    }


Outroduction:

In this section, we know why a Model is created, and what are Data Annotations. Without Data Annotations are cannot enforce rules over the Models. The rules can be as simple as Primary Key and Foreign Key rules to connect two Models. In the next section, we will see how more on Entity Framework. Navigate to the next section here: 

Happy Coding!