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

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

Embed Size (px)

Citation preview

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

Part 06 – A More Complex Data Model

Entity Framework and MVCNTPCUG

Tom Perkins

Page 2: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 3: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

THE COMPLETED DATA MODEL

Page 4: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 5: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 6: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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<Enrollment> Enrollments { get; set; } }}

Page 7: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 8: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Run

• Student Page – No longer displays time

• Click on Edit– Enrollment date has a Date Selector displayed

(HTML5)

Page 9: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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]*$")]

Page 10: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

<timestamp>_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.

Page 11: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins
Page 12: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

FirstMidName FirstName

Page 13: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Server Explorer

• Open the Student table

Page 14: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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<Enrollment> Enrollments { get; set; } }}

Page 15: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 16: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

The Instructor Entity

• Do Activity 06-6

Page 17: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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<Course> Courses { get; set; } public virtual OfficeAssignment OfficeAssignment { get; set; } }}

Activity 06-6 – Create Instructor Entity

Page 18: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Courses and OfficeAssignment Navigation Properties

• Assigned as virtual lazy loading• If a navigation property can hold multiple

entities, its type must implement the iCollection<T> interface

• Each instructor may teach multiple classes• Instructor has single office – null if no office assigned

Page 19: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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.

Page 20: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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 <classnameID>

– Key attribute identifies InstructorID as the primary key

– Primary key is also its foreign key

Page 21: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 22: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Modify the Course Entity

• Do Activity 06-8 Modify the Course Entity

Page 23: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Notes for 06-8Modify 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.

Page 24: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Create the Department Entity

• Do Activity 06-9 Department Entity

Page 25: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 26: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Modify the Enrollment Entity

Page 27: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 28: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Generated by Entity Framework Power Tools

Page 29: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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

Page 30: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

Entity Diagram Showing Relationships

Page 31: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

MODIFY THE DATA MODEL BY ADDING CODE TO THE DATABASE CONTEXT

Page 32: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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<Course>() .HasMany(c => c.Instructors).WithMany(i => i.Courses) .Map(t => t.MapLeftKey("CourseID") .MapRightKey("InstructorID") .ToTable("CourseInstructor"));

Page 33: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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.

Page 34: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

SEED THE DATABASE WITH TEST DATA

Page 35: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

SEED THE DATABASE

• Do ACTIVITY 06-12• Note creation of the Course entity– Initializes Instructors navigation property as an

empty collection• Instructors = new List<Instructor>()

– Makes it possible to add new instructor entities related to this course by using the Instructors.Add method.

Page 36: Part 06 – A More Complex Data Model Entity Framework and MVC NTPCUG Tom Perkins

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'.