NET 6 - Entities
Last modified: March 25, 2022A Entity/Model is a class file that has both properties and methods and it is used to get and set the data. A Model is one of the parts of the MVC (Model, View, and Controller) pattern. In ASP.NET 5, the model class are used with Entity Framework Core (EF Core) to work with a database and used to generate the database table through migration. EF Core is an ORM (object-relational mapping).
In this tutorial, we are using model classes that are created first (code first) and then database later through the migration process. However, it is also possible to generate a model from an existing database (database first).
1. Add Entities
- Select TicketingSystem.Core project
- Delete Class1.cs class file
- Create an Entities folder
- Add new Event Entity by right-clicking on TicketingSystem.Core project add new class as shown below
Give Event as filename
Below is the class file for Event, where we have Id as primary key ([key]). We have Name, Location, and Date properties. For the Date property, we annotate that it is the only Date. One event has many booking (one to many relationships), we add public ICollection<EventBooking> EventBooking { get; set; }
We will create EventBooking class file shortly.
public class Event
{
[Key] //mark it as Primary Key
public string Id { get; set; }
public string Name { get; set; }
public string Location { get; set; }
[DataType(DataType.Date)]
public DateTime Date { get; set; }
public ICollection<EventBooking> EventBooking { get; set; }
}
- Add another class file called EventBooking with the same steps as below.
EventBooking
Create EventBooking Model class file. [NotMapped] attribute to exclude a field from your model so that during the database migration it will be excluded.
public class EventBooking
{
[Key]
public string Id { get; set; }
public string Email { get; set; }
[NotMapped]
public string EventName { get; set; }
public string EventId { get; set; }
public Event Event { get; set; }
}