Exercise 5-7: contoso University campus Management System (implement inheritance)

Source: Internet
Author: User

In the previous tutorial, you have been able to handle concurrency exceptions. This tutorial shows how to implement inheritance in the data model.

In object-oriented programming, you can clear redundant code through inheritance. In this tutorial, you will modify the instructor and student classes so that they can be derived from the person class containing properties similar to lastname. You do not need to modify the web page. You need to modify some code, which will be automatically reflected into the database.

1. Single Table inheritance (Table-per-hierarchy) vs type table (table-per-type) Inheritance

In object-oriented programming, you can use inheritance for related classes to make work easier. For example, the instructor uctor and student classes share multiple attributes in the school data model, resulting in redundant code.

Suppose you want to clear the redundant code generated by the attributes shared between the instructor's uctor and student. You can create a person base class that only contains the attributes they share. Then, the teacher's primary uctor and student classes are derived from the person base class, as shown in.

 

In the database, this inheritance structure can have multiple forms. You can create a table named person, which contains all the information of instructors and students. It includes attributes they own (for example, teachers' hiredate and students' enrollmentdate) and their common attributes (for example, lastname and firstname ). Generally, you also need a discriminator to identify the type of the current row. (Here, the content of the logo column is "instructor" to indicate teachers and student to indicate students)

The Mode for generating an Object Inheritance structure using a single database table is called the single table inheritance mode TPH (Table-per-hierarchy ). Another way is to make the database look similar to the inheritance structure. For example, the person table only contains the name attributes they all share, and saves the time to the independent uctor and student tables respectively.

The schema that corresponds to a database table is called the type table TPT inheritance (Table per type ). In EF, TPH inheritance has better performance than TPT inheritance, because TPT inheritance requires complex connection queries. This tutorial demonstrates how to implement TPH inheritance. Follow these steps:

  • Create the person class and derive the policuctor and student classes from the person class.
  • Add the ing code from the model to the database in the database context class.
  • Change instructorid and studentid in the project to use personid.
8-2 create person class

In the model folder, create person. CS and replace the original code with the following code.

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;namespace ContosoUniversity.Models{    public abstract class Person    {        [Key]        public int PersonID { get; set; }        [Required(ErrorMessage = "Last name is required.")]        [Display(Name="Last Name")]        [MaxLength(50)]        public string LastName { get; set; }        [Required(ErrorMessage = "First name is required.")]        [Column("FirstName")]        [Display(Name = "First Name")]        [MaxLength(50)]        public string FirstMidName { get; set; }        public string FullName         {            get            {                return LastName + ", " + FirstMidName;            }        }    }}

In the policuctor. CS file, the policuctor is derived from person and the key and name fields are deleted. The Code is as follows.

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;namespace ContosoUniversity.Models{    public class Instructor : Person    {        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]        [Required(ErrorMessage = "Hire date is required.")]        [Display(Name = "Hire Date")]        public DateTime? HireDate { get; set; }        public virtual ICollection<Course> Courses { get; set; }              public virtual OfficeAssignment OfficeAssignment { get; set; }    }}

Modify the student. CS file similarly. The modified student class is as follows.

using System;using System.Collections.Generic;using System.ComponentModel.DataAnnotations;namespace ContosoUniversity.Models{    public class Student : Person    {        [Required(ErrorMessage = "Enrollment date is required.")]        [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]        [Display(Name = "Enrollment Date")]        public DateTime? EnrollmentDate { get; set; }        public virtual ICollection<Enrollment> Enrollments { get; set; }    }}
8-3 Add the person entity type to the model

In the schoolcontext. CS file, add a dbset attribute to the person object type.

public DbSet<Person> People { get; set; }

This is how to configure TPH in EF to inherit all the work that needs to be done. As you can see, when the database is rebuilt, EF will automatically create the person table.

8-4 modify instructorid and studentid to personid

In the schoolcontext. CS file, modify maprightkey ("instructorid") to maprightkey ("personid") in the instructor's ing statement for the course ").

modelBuilder.Entity<Course>()    .HasMany(c => c.Instructors).WithMany(i => i.Courses)    .Map(t => t.MapLeftKey("CourseID")    .MapRightKey("PersonID")    .ToTable("CourseInstructor"));

This modification is not necessary. It only modifies the name of instructorid in multiple-to-multiple join tables. If you keep the name as instructorid, the program can still work normally. Next, perform a global replacement (all files in the project), change instructorid to personid, and change studentid to personid. Be case sensitive. (This example demonstrates the disadvantage of using the class name and ID as the primary key. If you do not use the class name and ID as the primary key, you do not need to rename it here)

8-5 modify the value of the primary key in the initialization Tool

In schoolinitializer. CS, the Code assumes that the primary key numbers of student and uctor entities are separated. This is still true for student entities (they are still from 1 to 8), but for the uctor entity, it will not change from 1-5 to 9-13, because the code in the initialization class adds the instructor to the student in the same table. Use the following code to modify the code in the Department and officeassignment entities to use the new instructor ID.

var departments = new List<Department>{    new Department { Name = "English",     Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), PersonID = 9 },    new Department { Name = "Mathematics", Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), PersonID = 10 },    new Department { Name = "Engineering", Budget = 350000, StartDate = DateTime.Parse("2007-09-01"), PersonID = 11 },    new Department { Name = "Economics",   Budget = 100000, StartDate = DateTime.Parse("2007-09-01"), PersonID = 12 }};
var officeAssignments = new List<OfficeAssignment>{    new OfficeAssignment { PersonID = 9, Location = "Smith 17" },    new OfficeAssignment { PersonID = 10, Location = "Gowan 27" },    new OfficeAssignment { PersonID = 11, Location = "Thompson 304" },};
8-6 adjust officeassignment to delayed Loading

In the current version, EF uses the derived class after the TPH inheritance mode for navigation attributes. The pre-loading mode is not supported in the one-to-one or zero-to-zero relationship. This is a problem for the officeassignment attribute on the policuctor object. To solve this problem, you need to delete the preload processing used on this attribute. In the instructorcontroller. CS file, delete the following code that appears three times.

 .Include(i => i.OfficeAssignment)
8-7 testing

Run the program and check it on each page. All the work is the same as before. On solution manager, double-click School. open the SDF database in the server resource manager and expand school. then select tables. You will see that the student and uctor tables have been replaced by the person table. Expand the person table and you will see all the columns in the original student and uctor, plus the discriminator column.

Shows the structure of the new school database.

For the person, student, and uctor classes, TPH is used to implement inheritance. For more information about other inheritance structures, see the Morteza manavi blog inheritance mapping strategies. In the next tutorial, you will learn how to implement the warehousing and unit model.

Exercise 5-7: contoso University campus Management System (implement inheritance)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.