Add a model

Add a model to an ASP.NET Core MVC app

In this topic, classes are added for managing movies in a collection. These classes are the "Model" part of the MVC app.

These model classes can be used with any object-relational mapping (ORM) framework that simplifies the data access code that you have to write.

The model classes created are known as POCO classes, from Plain Old CLR Objects. POCO classes don't have any dependency on any ORM. They only define the properties of the data to be stored in the database.

Add a data model class

Right-click the Models folder > Add > Class. Name the file Movie.cs

Update the Models/Movie.cs file with the following code:

using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models;

public class Movie
{
    public int Id { get; set; }
    public string? Title { get; set; }
    [DataType(DataType.Date)]
    public DateTime ReleaseDate { get; set; }
    public string? Genre { get; set; }
    public decimal Price { get; set; }
}

What is this class about?

The Movie class contains an Id field, which is required by the database for the primary key.

The DataType attribute on ReleaseDate specifies the type of the data (Date). With this attribute:

  • The user isn't required to enter time information in the date field.

  • Only the date is displayed, not time information.

DataAnnotations are covered in a later tutorial.

The question mark after string indicates that the property is nullable. For more information, see Nullable reference types

Last updated