Creating a complex data model with the previous data model in ASP.NET is actually a challenging task.
The model in general looks like this:
It is not “extremely” complex, but it is something bigger than the previous 3 tables that we had before. Thus, in this tutorial some additional classes were added – a class per table. The seeding method was changed (twice actually), in order to seed data to the classes and a lot of data annotations were used, in order to display the data from the tables the way it was intended. E.g. in the Enrollments.cs entity, the annotation [DisplayFormat(NullDisplayText="No grade")] was used to display “no grade” when there was no entry for a grade in the DB. This is how the Student.cs class looks like with the annotations:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class Student { public int Id { get; set; } [Required] [StringLength(50, MinimumLength=1)] [Display(Name="Last Name")] public string LastName { get; set; } [StringLength(50, MinimumLength = 1)] [Column("FirstName")] [Display(Name="First Name")] public string FirstMidName { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString ="{0:yyyy-MM-dd}",ApplyFormatInEditMode = true)] [Display(Name="Enrollment Date")] public DateTime EnrollmentDate { get; set; } [Display(Name = "Full Name")] public string FullName { get { return LastName + ", " + FirstMidName; } } public ICollection<Enrollment> Enrollments{ get; set; } } } |
At the end of the video, the SQL written to display all courses and all teachers is this one:
1 2 3 4 5 |
SELECT i.LastName, c.Title FROM Instructores i LEFT OUTER JOIN AsignacionesDeCurso adc ON adc.InstructorId = i.ID LEFT OUTER JOIN Cursos c ON c.CourseId = adc.CourseId |
The rest of the classes are available in GitHub here – https://github.com/Vitosh/ASP/tree/master/EFCoreAsp.NetMvcWebApp/ContosoUniversity005
Enjoy!