Presentation is loading. Please wait.

Presentation is loading. Please wait.

Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins.

Similar presentations


Presentation on theme: "Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins."— Presentation transcript:

1 Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

2 A More Complex Data Model Objectives Add more entities and relationships to the Data Model Customize the data model by specifying rules for – Formatting – Validation – Database mapping Customize the data model by – Adding attributes to entity classes – Adding code to the database context class

3 THE COMPLETED DATA MODEL

4 Use Attributes to Customize the Data Model Modify Existing Entity Classes with attributes Add new entity classes Attributes we’ll examine – DataType – StringLength – Column – Required – Key – ForeignKey – DatabaseGenerated

5 Student Enrollment Dates Currently displaying time also – all pages that display the Enrollment date To display date only, add an attribute to the EnrollmentDate property in the Student Class

6 Add attributes to the EnrollmentDate Property Do Activity 06-1. In Models\Student.cs, add a using statement for the System.ComponentModel.DataAnnotations namespace and add DataType and DisplayFormat attributes to the EnrollmentDate property, as shown in the following example: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace ContosoUniversity.Models { public class Student { public int ID { get; set; } public string LastName { get; set; } public string FirstMidName { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] public DateTime EnrollmentDate { get; set; } public virtual ICollection Enrollments { get; set; } }

7 DataType Attribute DataType. (enumeration) – Date – Time – Currency – Email Address – CreditCard number – Image Can automatically provide some features –.EmailAddress  mailto: link –.Date  date selector for HTML5 browsers Does not supply format for date – specify through DisplayFormat attribute

8 Run Student Page – No longer displays time Click on Edit – Enrollment date has a Date Selector displayed (HTML5)

9 StringLength Attribute Sets Maximum Length of string in database Minimum value can also be specified – Has no effect on database schema Do Activity 06-2. StringLength does not validate an empty string. You can use the RegularExpression attribute to check the first character as upper-case and remaining characters to be alphabetical – [RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]

10 Effects of Changing the Max Field Lengths Run the App and click the Students tab. You get an error (see below) The database schema needs to be changed. Do Activity 06-3 This creates a file _maxLengthOnNames.cs – Up method contains code to update the database – Update-database statement ran that code. Try to create a student with a name longer than 50 characters.

11

12 The Column Attribute Control mapping of properties and classes to the database Database names are created by default from the property name Objective: Map FirstMidName property in entity class to FirstName column in the database. Do Activity 06-4. Classes and Properties Database FirstMidNameFirstName

13 Server Explorer Open the Student table

14 Complete the Student Entity Do Activity 06-05 In Models\Student.cs, replace the code you added earlier with the following code. The changes are highlighted. 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)] [Display(Name = "Last Name")] public string LastName { get; set; } [Required] [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")] [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 virtual ICollection Enrollments { get; set; } }

15 Notes for Attributes in Activity 06-5 Required – Makes field required – Not needed for value types (cannot be null) Date Time Double Float Display – change captions on text boxes FullName – calculated field, not in database – Needs Property Accessor only

16 The Instructor Entity Do Activity 06-6

17 Create Models\Instructor.cs, replacing the template code with the following code: using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class Instructor { public int ID { get; set; } [Required] [Display(Name = "Last Name")] [StringLength(50)] public string LastName { get; set; } [Required] [Column("FirstName")] [Display(Name = "First Name")] [StringLength(50)] public string FirstMidName { get; set; } [DataType(DataType.Date)] [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)] [Display(Name = "Hire Date")] public DateTime HireDate { get; set; } [Display(Name = "Full Name")] public string FullName { get { return LastName + ", " + FirstMidName; } } public virtual ICollection Courses { get; set; } public virtual OfficeAssignment OfficeAssignment { get; set; } } Activity 06-6 – Create Instructor Entity

18 Courses and OfficeAssignment Navigation Properties Assigned as virtual  lazy loading If a navigation property can hold multiple entities, its type must implement the iCollection interface Each instructor may teach multiple classes Instructor has single office – null if no office assigned

19 The OfficeAssignment Entity Do Activity 06-7 Create Models\OfficeAssignment.cs with the following code: using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace ContosoUniversity.Models { public class OfficeAssignment { [Key] [ForeignKey("Instructor")] public int InstructorID { get; set; } [StringLength(50)] [Display(Name = "Office Location")] public string Location { get; set; } public virtual Instructor Instructor { get; set; } } Build the project, which saves your changes and verifies you haven't made any copy and paste errors the compiler can catch.

20 Notes for Activity 06-7 Build Office Assignment Entity Key attribute – One to zero or one relationship between Instructor and OfficeAssignment entities – Primary key cannot be discerned by Entity Framework It doesn’t follow pattern of ID or – Key attribute identifies InstructorID as the primary key – Primary key is also its foreign key

21 Notes for Activity 06-7 Build Office Assignment Entity ForeignKey attribute – Must be applied to the dependent class to establish a one-to-one or one-to-many relationship The Instructor Navigation property – Non-nullable – an office must be assigned to an instructor before one of these entities can exist

22 Modify the Course Entity Do Activity 06-8 Modify the Course Entity

23 Notes for 06-8 Modify the Course Entity Course entity has a Department navigation property – Therefore, the ForeignKey attribute does not need to be specified for the Department column. DatabaseGenerated attribute –.Option.None  Primary key values for CourseID are provided by the user rather than generated by the database – User specified course numbers: 1000 series for one department; 2000 series for another dept – entered by user Course has many students  nav prop is a collection Course may be taught by multiple instructors  nav prop is a collection.

24 Create the Department Entity Do Activity 06-9 Department Entity

25 Notes for Activity 06-9 Department Entity Column attribute used to change database column to SQL money datatype. Department may or may not have an administrator Administrator is always an Instructor InstructorID property is included as a foreign key to the Department entity (nullable) Navigation property is named Administrator but contains an Instructor entity A department may have many courses

26 Modify the Enrollment Entity

27 Notes on Enrollment Entity Foreign key and Navigation Properties reflect: – An enrollment record is for a single course Hence, a CourseID foreign key property and a course navigation property – An enrollment record is for a single student Hence, a StudentID ForeignKey Property and a student navigation property “Table with payload” – a many-to-many join table with additional data, such as the Enrollment entity

28 Generated by Entity Framework Power Tools

29 If there were no Grade in Enrollments There would be a many-to-many relationship between Courses and Instructors You would not have to specify an entity for Enrollments. Entity Framework would automatically generate a join table

30 Entity Diagram Showing Relationships

31 MODIFY THE DATA MODEL BY ADDING CODE TO THE DATABASE CONTEXT

32 FLUENT API You can string a series of method calls together in a single statement (below) Some db mapping can’t be done with attributes Fluent API can keep entity classes “clean” Recommended practice: Choose Fluent API or use of attributes method and be as consistent as possible modelBuilder.Entity ().HasMany(c => c.Instructors).WithMany(i => i.Courses).Map(t => t.MapLeftKey("CourseID").MapRightKey("InstructorID").ToTable("CourseInstructor"));

33 Fluent API Do Activity 06-11: Configure names in many- to-many relationship between Courses and Instructors For Course and Instructor relationship, code specifies table and column names for the join table.

34 SEED THE DATABASE WITH TEST DATA

35 SEED THE DATABASE Do ACTIVITY 06-12 Note creation of the Course entity – Initializes Instructors navigation property as an empty collection Instructors = new List () – Makes it possible to add new instructor entities related to this course by using the Instructors.Add method.

36 Add a Migration Do Activity 06-13: Do a Migration. (Do not do an update yet.) See below for error if update is tried at this point You must insert stub data to satisfy foreign key constraints. Do Activity 06-14. The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_dbo.Course_dbo.Department_DepartmentID". The conflict occurred in database "ContosoUniversity", table "dbo.Department", column 'DepartmentID'.


Download ppt "Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins."

Similar presentations


Ads by Google