In this article we will create something new in our project. We will use the “Code First” approach, that is, “first” will write the code. It seems trite to say, but Visual Studio allows, for example, even the “Database First” approach.
Go into the Model directory and create a new class, for example Student.cs.
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MySite.Models { public class Student { } }
Add this namespace
using System.ComponentModel.DataAnnotations.Schema;
Our model / class is the representation, through its properties, a table that we will build into the database. First of all, let’s talk to the class as it is called to the table that we are preparing.
[Table("STUDENTS")] public class Student { }
Then we create the properties – fields of the table. Add this namespace:
using System.ComponentModel.DataAnnotations;
our table consists of three fields
[Table("STUDENTS")] public class Student { [Key] [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)] public int ID { get; set; } [Required] [StringLength(200)] [Display(Name = "Name")] public string NAME { get; set; } [StringLength(300)] [Display(Name = "Surname")] public string SURNAME { get; set; } }
The DataAnnotation, written on properties, defining the characteristics of the table fields: ID is the primary key (key), and SQLServer be responsible for assigning the number (DatabaseGeneratedOption.Identity). NAME is a required field (Required) of length 200, the description of which, during a display, it will be “Name” .etc.
Now we must add to DbContext the presence of this table. Open the ApplicationDbContext class and add, as a property, the new table:
public DbSet<Student> Students { get; set; }
Try running the application and perform a login to test that everything is working. Go to the database and built the table complying with his name and the names of the properties of the class.