"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Creating a More Complex Data Model for an ASP.NET MVC Application (4 of 10)

by Tom Dykstra

Download Completed Project

The Contoso University sample web application demonstrates how to create ASP.NET MVC 4 applications using the Entity Framework 5 Code First and Visual Studio 2012. For information about the tutorial series, see the first tutorial in the series. You can start the tutorial series from the beginning or download a starter project for this chapter and start here.

[!NOTE]

If you run into a problem you can’t resolve, download the completed chapter and try to reproduce your problem. You can generally find the solution to the problem by comparing your code to the completed code. For some common errors and how to solve them, see Errors and Workarounds.

In the previous tutorials you worked with a simple data model that was composed of three entities. In this tutorial you’ll add more entities and relationships and you’ll customize the data model by specifying formatting, validation, and database mapping rules. You’ll see two ways to customize the data model: by adding attributes to entity classes and by adding code to the database context class.

When you’re finished, the entity classes will make up the completed data model that’s shown in the following illustration:

School_class_diagram
School_class_diagram

Customize the Data Model by Using Attributes

In this section you’ll see how to customize the data model by using attributes that specify formatting, validation, and database mapping rules. Then in several of the following sections you’ll create the complete School data model by adding attributes to the classes you already created and creating new classes for the remaining entity types in the model.

The DataType Attribute

For student enrollment dates, all of the web pages currently display the time along with the date, although all you care about for this field is the date. By using data annotation attributes, you can make one code change that will fix the display format in every view that shows the data. To see an example of how to do that, you’ll add an attribute to the EnrollmentDate property in the Student class.

In Models.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:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:   
   5:  namespace ContosoUniversity.Models
   6:  {
   7:      public class Student
   8:      {
   9:          public int StudentID { get; set; }
  10:          public string LastName { get; set; }
  11:          public string FirstMidName { get; set; }
  12:          
  13:          [DataType(DataType.Date)]
  14:          [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  15:          public DateTime EnrollmentDate { get; set; }
  16:          
  17:          public virtual ICollection<Enrollment> Enrollments { get; set; }
  18:      }
  19:  }

The DataType attribute is used to specify a data type that is more specific than the database intrinsic type. In this case we only want to keep track of the date, not the date and time. The DataType Enumeration provides for many data types, such as Date, Time, PhoneNumber, Currency, EmailAddress and more. The DataType attribute can also enable the application to automatically provide type-specific features. For example, a mailto: link can be created for DataType.EmailAddress, and a date selector can be provided for DataType.Date in browsers that support HTML5. The DataType attributes emits HTML 5 data- (pronounced data dash) attributes that HTML 5 browsers can understand. The DataType attributes do not provide any validation.

DataType.Date does not specify the format of the date that is displayed. By default, the data field is displayed according to the default formats based on the server’s CultureInfo.

The DisplayFormat attribute is used to explicitly specify the date format:

[!code-csharpMain]

   1:  [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
   2:  public DateTime EnrollmentDate { get; set; }

The ApplyFormatInEditMode setting specifies that the specified formatting should also be applied when the value is displayed in a text box for editing. (You might not want that for some fields — for example, for currency values, you might not want the currency symbol in the text box for editing.)

You can use the DisplayFormat attribute by itself, but it’s generally a good idea to use the DataType attribute also. The DataType attribute conveys the semantics of the data as opposed to how to render it on a screen, and provides the following benefits that you don’t get with DisplayFormat:

If you use the DataType attribute with a date field, you have to specify the DisplayFormat attribute also in order to ensure that the field renders correctly in Chrome browsers. For more information, see this StackOverflow thread.

Run the Student Index page again and notice that times are no longer displayed for the enrollment dates. The same will be true for any view that uses the Student model.

Students_index_page_with_formatted_date
Students_index_page_with_formatted_date

The StringLengthAttribute

You can also specify data validation rules and messages using attributes. Suppose you want to ensure that users don’t enter more than 50 characters for a name. To add this limitation, add StringLength attributes to the LastName and FirstMidName properties, as shown in the following example:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:   
   5:  namespace ContosoUniversity.Models
   6:  {
   7:      public class Student
   8:      {
   9:          public int StudentID { get; set; }
  10:          [StringLength(50)]
  11:          public string LastName { get; set; }
  12:          [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
  13:          public string FirstMidName { get; set; }
  14:          [DataType(DataType.Date)]
  15:          [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  16:          public DateTime EnrollmentDate { get; set; }
  17:          
  18:          public virtual ICollection<Enrollment> Enrollments { get; set; }
  19:      }
  20:  }

The StringLength attribute won’t prevent a user from entering white space for a name. You can use the RegularExpression attribute to apply restrictions to the input. For example the following code requires the first character to be upper case and the remaining characters to be alphabetical:

[RegularExpression(@"^[A-Z]+[a-zA-Z''-'\s]*$")]

The MaxLength attribute provides similar functionality to the StringLength attribute but doesn’t provide client side validation.

Run the application and click the Students tab. You get the following error:

The model backing the ‘SchoolContext’ context has changed since the database was created. Consider using Code First Migrations to update the database (https://go.microsoft.com/fwlink/?LinkId=238269).

The database model has changed in a way that requires a change in the database schema, and Entity Framework detected that. You’ll use migrations to update the schema without losing any data that you added to the database by using the UI. If you changed data that was created by the Seed method, that will be changed back to its original state because of the AddOrUpdate method that you’re using in the Seed method. (AddOrUpdate is equivalent to an “upsert” operation from database terminology.)

In the Package Manager Console (PMC), enter the following commands:

[!code-consoleMain]

   1:  add-migration MaxLengthOnNames
   2:  update-database

The add-migration MaxLengthOnNames command creates a file named <timeStamp>_MaxLengthOnNames.cs. This file contains code that will update the database to match the current data model. The timestamp prepended to the migrations file name is used by Entity Framework to order the migrations. After you have created multiple migrations, if you drop the database, or if you deploy the project by using Migrations, all of the migrations are applied in the order in which they were created.

Run the Create page, and enter either name longer than 50 characters. As soon as you exceed 50 characters, client side validation immediately shows an error message.

client side val error
client side val error

The Column Attribute

You can also use attributes to control how your classes and properties are mapped to the database. Suppose you had used the name FirstMidName for the first-name field because the field might also contain a middle name. But you want the database column to be named FirstName, because users who will be writing ad-hoc queries against the database are accustomed to that name. To make this mapping, you can use the Column attribute.

The Column attribute specifies that when the database is created, the column of the Student table that maps to the FirstMidName property will be named FirstName. In other words, when your code refers to Student.FirstMidName, the data will come from or be updated in the FirstName column of the Student table. If you don’t specify column names, they are given the same name as the property name.

Add a using statement for System.ComponentModel.DataAnnotations.Schema and the column name attribute to the FirstMidName property, as shown in the following highlighted code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.ComponentModel.DataAnnotations.Schema;
   5:   
   6:  namespace ContosoUniversity.Models
   7:  {
   8:      public class Student
   9:      {
  10:          public int StudentID { get; set; }
  11:          [StringLength(50)]       
  12:          public string LastName { get; set; }
  13:          [StringLength(50, ErrorMessage = "First name cannot be longer than 50 characters.")]
  14:          [Column("FirstName")]
  15:          public string FirstMidName { get; set; }
  16:          [DataType(DataType.Date)]
  17:          [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  18:          public DateTime EnrollmentDate { get; set; }
  19:          
  20:          public virtual ICollection<Enrollment> Enrollments { get; set; }
  21:      }
  22:  }

The addition of the Column attribute changes the model backing the SchoolContext, so it won’t match the database. Enter the following commands in the PMC to create another migration:

[!code-consoleMain]

   1:  add-migration ColumnFirstName
   2:  update-database

In Server Explorer (Database Explorer if you are using Express for Web), double-click the Student table.

The following image shows the original column name as it was before you applied the first two migrations. In addition to the column name changing from FirstMidName to FirstName, the two name columns have changed from MAX length to 50 characters.

You can also make database mapping changes using the Fluent API, as you’ll see later in this tutorial.

[!NOTE] If you try to compile before you finish creating all of these entity classes, you might get compiler errors.

Create the Instructor Entity

Instructor_entity
Instructor_entity

Create Models.cs, replacing the template code with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.ComponentModel.DataAnnotations.Schema;
   5:   
   6:  namespace ContosoUniversity.Models
   7:  {
   8:      public class Instructor
   9:      {
  10:          public int InstructorID { get; set; }
  11:   
  12:          [Required]
  13:          [Display(Name = "Last Name")]
  14:          [StringLength(50)]
  15:          public string LastName { get; set; }
  16:   
  17:          [Required]
  18:          [Column("FirstName")]
  19:          [Display(Name = "First Name")]
  20:          [StringLength(50)]
  21:          public string FirstMidName { get; set; }
  22:   
  23:          [DataType(DataType.Date)]
  24:          [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  25:          [Display(Name = "Hire Date")]
  26:          public DateTime HireDate { get; set; }
  27:   
  28:          public string FullName
  29:          {
  30:              get { return LastName + ", " + FirstMidName; }
  31:          }
  32:   
  33:          public virtual ICollection<Course> Courses { get; set; }
  34:          public virtual OfficeAssignment OfficeAssignment { get; set; }
  35:      }
  36:  }

Notice that several properties are the same in the Student and Instructor entities. In the Implementing Inheritance tutorial later in this series, you’ll refactor using inheritance to eliminate this redundancy.

The Required and Display Attributes

The attributes on the LastName property specify that it’s a required field, that the caption for the text box should be “Last Name” (instead of the property name, which would be “LastName” with no space), and that the value can’t be longer than 50 characters.

[!code-csharpMain]

   1:  [Required]
   2:  [Display(Name="Last Name")]
   3:  [StringLength(50)]
   4:  public string LastName { get; set; }

The StringLength attribute sets the maximum length in the database and provides client side and server side validation for ASP.NET MVC. You can also specify the minimum string length in this attribute, but the minimum value has no impact on the database schema. The Required attribute is not needed for value types such as DateTime, int, double, and float. Value types cannot be assigned a null value, so they are inherently required. You could remove the Required attribute and replace it with a minimum length parameter for the StringLength attribute:

[!code-csharpMain]

   1:  [Display(Name = "Last Name")]
   2:  [StringLength(50, MinimumLength=1)]
   3:  public string LastName { get; set; }

You can put multiple attributes on one line, so you could also write the instructor class as follows:

[!code-csharpMain]

   1:  public class Instructor
   2:  {
   3:     public int InstructorID { get; set; }
   4:   
   5:     [Display(Name = "Last Name"),StringLength(50, MinimumLength=1)]
   6:     public string LastName { get; set; }
   7:   
   8:     [Column("FirstName"),Display(Name = "First Name"),StringLength(50, MinimumLength=1)]
   9:     public string FirstMidName { get; set; }
  10:   
  11:     [DataType(DataType.Date),Display(Name = "Hire Date"),DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  12:     public DateTime HireDate { get; set; }
  13:   
  14:     public string FullName
  15:     {
  16:        get { return LastName + ", " + FirstMidName; }
  17:     }
  18:   
  19:     public virtual ICollection<Course> Courses { get; set; }
  20:     public virtual OfficeAssignment OfficeAssignment { get; set; }
  21:  }

The FullName Calculated Property

FullName is a calculated property that returns a value that’s created by concatenating two other properties. Therefore it has only a get accessor, and no FullName column will be generated in the database.

[!code-csharpMain]

   1:  public string FullName
   2:  {
   3:      get { return LastName + ", " + FirstMidName; }
   4:  }

The Courses and OfficeAssignment Navigation Properties

The Courses and OfficeAssignment properties are navigation properties. As was explained earlier, they are typically defined as virtual so that they can take advantage of an Entity Framework feature called lazy loading. In addition, if a navigation property can hold multiple entities, its type must implement the ICollection<T> Interface. (For example IList<T> qualifies but not IEnumerable<T> because IEnumerable<T> doesn’t implement Add.

An instructor can teach any number of courses, so Courses is defined as a collection of Course entities. Our business rules state an instructor can only have at most one office, so OfficeAssignment is defined as a single OfficeAssignment entity (which may be null if no office is assigned).

[!code-csharpMain]

   1:  public virtual ICollection<Course> Courses { get; set; }
   2:  public virtual OfficeAssignment OfficeAssignment { get; set; }

Create the OfficeAssignment Entity

OfficeAssignment_entity
OfficeAssignment_entity

Create Models.cs with the following code:

[!code-csharpMain]

   1:  using System.ComponentModel.DataAnnotations;
   2:  using System.ComponentModel.DataAnnotations.Schema;
   3:   
   4:  namespace ContosoUniversity.Models
   5:  {
   6:      public class OfficeAssignment
   7:      {
   8:          [Key]
   9:          [ForeignKey("Instructor")]
  10:          public int InstructorID { get; set; }
  11:          [StringLength(50)]
  12:          [Display(Name = "Office Location")]
  13:          public string Location { get; set; }
  14:   
  15:          public virtual Instructor Instructor { get; set; }
  16:      }
  17:  }

Build the project, which saves your changes and verifies you haven’t made any copy and paste errors the compiler can catch.

The Key Attribute

There’s a one-to-zero-or-one relationship between the Instructor and the OfficeAssignment entities. An office assignment only exists in relation to the instructor it’s assigned to, and therefore its primary key is also its foreign key to the Instructor entity. But the Entity Framework can’t automatically recognize InstructorID as the primary key of this entity because its name doesn’t follow the ID or classname ID naming convention. Therefore, the Key attribute is used to identify it as the key:

[!code-csharpMain]

   1:  [Key]
   2:  [ForeignKey("Instructor")]
   3:  public int InstructorID { get; set; }

You can also use the Key attribute if the entity does have its own primary key but you want to name the property something different than classnameID or ID. By default EF treats the key as non-database-generated because the column is for an identifying relationship.

The ForeignKey Attribute

When there is a one-to-zero-or-one relationship or a one-to-one relationship between two entities (such as between OfficeAssignment and Instructor), EF can’t work out which end of the relationship is the principal and which end is dependent. One-to-one relationships have a reference navigation property in each class to the other class. The ForeignKey Attribute can be applied to the dependent class to establish the relationship. If you omit the ForeignKey Attribute, you get the following error when you try to create the migration:

Unable to determine the principal end of an association between the types ‘ContosoUniversity.Models.OfficeAssignment’ and ‘ContosoUniversity.Models.Instructor’. The principal end of this association must be explicitly configured using either the relationship fluent API or data annotations.

Later in the tutorial we’ll show how to configure this relationship with the fluent API.

The Instructor Navigation Property

The Instructor entity has a nullable OfficeAssignment navigation property (because an instructor might not have an office assignment), and the OfficeAssignment entity has a non-nullable Instructor navigation property (because an office assignment can’t exist without an instructor – InstructorID is non-nullable). When an Instructor entity has a related OfficeAssignment entity, each entity will have a reference to the other one in its navigation property.

You could put a [Required] attribute on the Instructor navigation property to specify that there must be a related instructor, but you don’t have to do that because the InstructorID foreign key (which is also the key to this table) is non-nullable.

Modify the Course Entity

Course_entity
Course_entity

In Models.cs, replace the code you added earlier with the following code:

[!code-csharpMain]

   1:  using System.Collections.Generic;
   2:  using System.ComponentModel.DataAnnotations;
   3:  using System.ComponentModel.DataAnnotations.Schema;
   4:   
   5:  namespace ContosoUniversity.Models
   6:  {
   7:     public class Course
   8:     {
   9:        [DatabaseGenerated(DatabaseGeneratedOption.None)]
  10:        [Display(Name = "Number")]
  11:        public int CourseID { get; set; }
  12:   
  13:        [StringLength(50, MinimumLength = 3)]
  14:        public string Title { get; set; }
  15:   
  16:        [Range(0, 5)]
  17:        public int Credits { get; set; }
  18:   
  19:        [Display(Name = "Department")]
  20:        public int DepartmentID { get; set; }
  21:   
  22:        public virtual Department Department { get; set; }
  23:        public virtual ICollection<Enrollment> Enrollments { get; set; }
  24:        public virtual ICollection<Instructor> Instructors { get; set; }
  25:     }
  26:  }

The course entity has a foreign key property DepartmentID which points to the related Department entity and it has a Department navigation property. The Entity Framework doesn’t require you to add a foreign key property to your data model when you have a navigation property for a related entity. EF automatically creates foreign keys in the database wherever they are needed. But having the foreign key in the data model can make updates simpler and more efficient. For example, when you fetch a course entity to edit, the Department entity is null if you don’t load it, so when you update the course entity, you would have to first fetch the Department entity. When the foreign key property DepartmentID is included in the data model, you don’t need to fetch the Department entity before you update.

The DatabaseGenerated Attribute

The DatabaseGenerated attribute with the None parameter on the CourseID property specifies that primary key values are provided by the user rather than generated by the database.

[!code-csharpMain]

   1:  [DatabaseGenerated(DatabaseGeneratedOption.None)]
   2:  [Display(Name = "Number")]
   3:  public int CourseID { get; set; }

By default, the Entity Framework assumes that primary key values are generated by the database. That’s what you want in most scenarios. However, for Course entities, you’ll use a user-specified course number such as a 1000 series for one department, a 2000 series for another department, and so on.

Foreign Key and Navigation Properties

The foreign key properties and navigation properties in the Course entity reflect the following relationships:

Creating the Department Entity

Department_entity
Department_entity

Create Models.cs with the following code:

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.ComponentModel.DataAnnotations.Schema;
   5:   
   6:  namespace ContosoUniversity.Models
   7:  {
   8:     public class Department
   9:     {
  10:        public int DepartmentID { get; set; }
  11:   
  12:        [StringLength(50, MinimumLength=3)]
  13:        public string Name { get; set; }
  14:   
  15:        [DataType(DataType.Currency)]
  16:        [Column(TypeName = "money")]
  17:        public decimal Budget { get; set; }
  18:   
  19:        [DataType(DataType.Date)]
  20:        public DateTime StartDate { get; set; }
  21:   
  22:        [Display(Name = "Administrator")]
  23:        public int? InstructorID { get; set; }
  24:   
  25:        public virtual Instructor Administrator { get; set; }
  26:        public virtual ICollection<Course> Courses { get; set; }
  27:     }
  28:  }

The Column Attribute

Earlier you used the Column attribute to change column name mapping. In the code for the Department entity, the Column attribute is being used to change SQL data type mapping so that the column will be defined using the SQL Server money type in the database:

[!code-csharpMain]

   1:  [Column(TypeName="money")]
   2:  public decimal Budget { get; set; }

Column mapping is generally not required, because the Entity Framework usually chooses the appropriate SQL Server data type based on the CLR type that you define for the property. The CLR decimal type maps to a SQL Server decimal type. But in this case you know that the column will be holding currency amounts, and the money data type is more appropriate for that.

Foreign Key and Navigation Properties

The foreign key and navigation properties reflect the following relationships:

[!NOTE] By convention, the Entity Framework enables cascade delete for non-nullable foreign keys and for many-to-many relationships. This can result in circular cascade delete rules, which will cause an exception when your initializer code runs. For example, if you didn’t define the Department.InstructorID property as nullable, you’d get the following exception message when the initializer runs: “The referential relationship will result in a cyclical reference that’s not allowed.” If your business rules required InstructorID property as non-nullable, you would have to use the following fluent API to disable cascade delete on the relationship:

[!code-csharpMain]

   1:  modelBuilder.Entity().HasRequired(d => d.Administrator).WithMany().WillCascadeOnDelete(false);

Modifying the Student Entity

Student_entity
Student_entity

In Models.cs, replace the code you added earlier with the following code. The changes are highlighted.

[!code-csharpMain]

   1:  using System;
   2:  using System.Collections.Generic;
   3:  using System.ComponentModel.DataAnnotations;
   4:  using System.ComponentModel.DataAnnotations.Schema;
   5:   
   6:  namespace ContosoUniversity.Models
   7:  {
   8:     public class Student
   9:     {
  10:        public int StudentID { get; set; }
  11:   
  12:        [StringLength(50, MinimumLength = 1)]
  13:        public string LastName { get; set; }
  14:   
  15:        [StringLength(50, MinimumLength = 1, ErrorMessage = "First name cannot be longer than 50 characters.")]
  16:        [Column("FirstName")]
  17:        public string FirstMidName { get; set; }
  18:   
  19:        [DataType(DataType.Date)]
  20:        [DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
  21:        [Display(Name = "Enrollment Date")]
  22:        public DateTime EnrollmentDate { get; set; }
  23:   
  24:        public string FullName
  25:        {
  26:           get { return LastName + ", " + FirstMidName; }
  27:        }
  28:   
  29:        public virtual ICollection<Enrollment> Enrollments { get; set; }
  30:     }
  31:  }

The Enrollment Entity

In Models.cs, replace the code you added earlier with the following code

[!code-csharpMain]

   1:  using System.ComponentModel.DataAnnotations;
   2:   
   3:  namespace ContosoUniversity.Models
   4:  {
   5:      public enum Grade
   6:      {
   7:          A, B, C, D, F
   8:      }
   9:   
  10:      public class Enrollment
  11:      {
  12:          public int EnrollmentID { get; set; }
  13:          public int CourseID { get; set; }
  14:          public int StudentID { get; set; }
  15:          
  16:          [DisplayFormat(NullDisplayText = "No grade")]
  17:          public Grade? Grade { get; set; }
  18:   
  19:          public virtual Course Course { get; set; }
  20:          public virtual Student Student { get; set; }
  21:      }
  22:  }

Foreign Key and Navigation Properties

The foreign key properties and navigation properties reflect the following relationships:

Many-to-Many Relationships

There’s a many-to-many relationship between the Student and Course entities, and the Enrollment entity functions as a many-to-many join table with payload in the database. This means that the Enrollment table contains additional data besides foreign keys for the joined tables (in this case, a primary key and a Grade property).

The following illustration shows what these relationships look like in an entity diagram. (This diagram was generated using the Entity Framework Power Tools; creating the diagram isn’t part of the tutorial, it’s just being used here as an illustration.)

Student-Course_many-to-many_relationship
Student-Course_many-to-many_relationship

Each relationship line has a 1 at one end and an asterisk (*) at the other, indicating a one-to-many relationship.

If the Enrollment table didn’t include grade information, it would only need to contain the two foreign keys CourseID and StudentID. In that case, it would correspond to a many-to-many join table without payload (or a pure join table) in the database, and you wouldn’t have to create a model class for it at all. The Instructor and Course entities have that kind of many-to-many relationship, and as you can see, there is no entity class between them:

Instructor-Course_many-to-many_relationship
Instructor-Course_many-to-many_relationship

A join table is required in the database, however, as shown in the following database diagram:

Instructor-Course_many-to-many_relationship_tables
Instructor-Course_many-to-many_relationship_tables

The Entity Framework automatically creates the CourseInstructor table, and you read and update it indirectly by reading and updating the Instructor.Courses and Course.Instructors navigation properties.

Entity Diagram Showing Relationships

The following illustration shows the diagram that the Entity Framework Power Tools create for the completed School model.

School_data_model_diagram
School_data_model_diagram

Besides the many-to-many relationship lines (* to *) and the one-to-many relationship lines (1 to *), you can see here the one-to-zero-or-one relationship line (1 to 0..1) between the Instructor and OfficeAssignment entities and the zero-or-one-to-many relationship line (0..1 to *) between the Instructor and Department entities.

Customize the Data Model by adding Code to the Database Context

Next you’ll add the new entities to the SchoolContext class and customize some of the mapping using fluent API calls. (The API is “fluent” because it’s often used by stringing a series of method calls together into a single statement.)

In this tutorial you’ll use the fluent API only for database mapping that you can’t do with attributes. However, you can also use the fluent API to specify most of the formatting, validation, and mapping rules that you can do by using attributes. Some attributes such as MinimumLength can’t be applied with the fluent API. As mentioned previously, MinimumLength doesn’t change the schema, it only applies a client and server side validation rule

Some developers prefer to use the fluent API exclusively so that they can keep their entity classes “clean.” You can mix attributes and fluent API if you want, and there are a few customizations that can only be done by using fluent API, but in general the recommended practice is to choose one of these two approaches and use that consistently as much as possible.

To add the new entities to the data model and perform database mapping that you didn’t do by using attributes, replace the code in DAL.cs with the following code:

[!code-csharpMain]

   1:  using ContosoUniversity.Models;
   2:  using System.Data.Entity;
   3:  using System.Data.Entity.ModelConfiguration.Conventions;
   4:   
   5:  namespace ContosoUniversity.DAL
   6:  {
   7:     public class SchoolContext : DbContext
   8:     {
   9:        public DbSet<Course> Courses { get; set; }
  10:        public DbSet<Department> Departments { get; set; }
  11:        public DbSet<Enrollment> Enrollments { get; set; }
  12:        public DbSet<Instructor> Instructors { get; set; }
  13:        public DbSet<Student> Students { get; set; }
  14:        public DbSet<OfficeAssignment> OfficeAssignments { get; set; }
  15:   
  16:        protected override void OnModelCreating(DbModelBuilder modelBuilder)
  17:        {
  18:           modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
  19:   
  20:           modelBuilder.Entity<Course>()
  21:               .HasMany(c => c.Instructors).WithMany(i => i.Courses)
  22:               .Map(t => t.MapLeftKey("CourseID")
  23:                   .MapRightKey("InstructorID")
  24:                   .ToTable("CourseInstructor"));
  25:        }
  26:     }
  27:  }

The new statement in the OnModelCreating method configures the many-to-many join table:

The following code provides an example of how you could have used fluent API instead of attributes to specify the relationship between the Instructor and OfficeAssignment entities:

[!code-csharpMain]

   1:  modelBuilder.Entity<Instructor>()
   2:      .HasOptional(p => p.OfficeAssignment).WithRequired(p => p.Instructor);

For information about what “fluent API” statements are doing behind the scenes, see the Fluent API blog post.

Seed the Database with Test Data

Replace the code in the Migrations.cs file with the following code in order to provide seed data for the new entities you’ve created.

[!code-csharpMain]

   1:  namespace ContosoUniversity.Migrations
   2:  {
   3:     using System;
   4:     using System.Collections.Generic;
   5:     using System.Data.Entity;
   6:     using System.Data.Entity.Migrations;
   7:     using System.Linq;
   8:     using ContosoUniversity.Models;
   9:     using ContosoUniversity.DAL;
  10:   
  11:     internal sealed class Configuration : DbMigrationsConfiguration<SchoolContext>
  12:     {
  13:        public Configuration()
  14:        {
  15:           AutomaticMigrationsEnabled = false;
  16:        }
  17:   
  18:        protected override void Seed(SchoolContext context)
  19:        {
  20:           var students = new List<Student>
  21:              {
  22:                  new Student { FirstMidName = "Carson",   LastName = "Alexander", 
  23:                      EnrollmentDate = DateTime.Parse("2010-09-01") },
  24:                  new Student { FirstMidName = "Meredith", LastName = "Alonso",    
  25:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
  26:                  new Student { FirstMidName = "Arturo",   LastName = "Anand",     
  27:                      EnrollmentDate = DateTime.Parse("2013-09-01") },
  28:                  new Student { FirstMidName = "Gytis",    LastName = "Barzdukas", 
  29:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
  30:                  new Student { FirstMidName = "Yan",      LastName = "Li",        
  31:                      EnrollmentDate = DateTime.Parse("2012-09-01") },
  32:                  new Student { FirstMidName = "Peggy",    LastName = "Justice",   
  33:                      EnrollmentDate = DateTime.Parse("2011-09-01") },
  34:                  new Student { FirstMidName = "Laura",    LastName = "Norman",    
  35:                      EnrollmentDate = DateTime.Parse("2013-09-01") },
  36:                  new Student { FirstMidName = "Nino",     LastName = "Olivetto",  
  37:                      EnrollmentDate = DateTime.Parse("2005-09-01") }
  38:              };
  39:   
  40:           students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
  41:           context.SaveChanges();
  42:   
  43:           var instructors = new List<Instructor>
  44:              {
  45:                  new Instructor { FirstMidName = "Kim",     LastName = "Abercrombie", 
  46:                      HireDate = DateTime.Parse("1995-03-11") },
  47:                  new Instructor { FirstMidName = "Fadi",    LastName = "Fakhouri",    
  48:                      HireDate = DateTime.Parse("2002-07-06") },
  49:                  new Instructor { FirstMidName = "Roger",   LastName = "Harui",       
  50:                      HireDate = DateTime.Parse("1998-07-01") },
  51:                  new Instructor { FirstMidName = "Candace", LastName = "Kapoor",      
  52:                      HireDate = DateTime.Parse("2001-01-15") },
  53:                  new Instructor { FirstMidName = "Roger",   LastName = "Zheng",      
  54:                      HireDate = DateTime.Parse("2004-02-12") }
  55:              };
  56:           instructors.ForEach(s => context.Instructors.AddOrUpdate(p => p.LastName, s));
  57:           context.SaveChanges();
  58:   
  59:           var departments = new List<Department>
  60:              {
  61:                  new Department { Name = "English",     Budget = 350000, 
  62:                      StartDate = DateTime.Parse("2007-09-01"), 
  63:                      InstructorID  = instructors.Single( i => i.LastName == "Abercrombie").InstructorID },
  64:                  new Department { Name = "Mathematics", Budget = 100000, 
  65:                      StartDate = DateTime.Parse("2007-09-01"), 
  66:                      InstructorID  = instructors.Single( i => i.LastName == "Fakhouri").InstructorID },
  67:                  new Department { Name = "Engineering", Budget = 350000, 
  68:                      StartDate = DateTime.Parse("2007-09-01"), 
  69:                      InstructorID  = instructors.Single( i => i.LastName == "Harui").InstructorID },
  70:                  new Department { Name = "Economics",   Budget = 100000, 
  71:                      StartDate = DateTime.Parse("2007-09-01"), 
  72:                      InstructorID  = instructors.Single( i => i.LastName == "Kapoor").InstructorID }
  73:              };
  74:           departments.ForEach(s => context.Departments.AddOrUpdate(p => p.Name, s));
  75:           context.SaveChanges();
  76:   
  77:           var courses = new List<Course>
  78:              {
  79:                  new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3,
  80:                    DepartmentID = departments.Single( s => s.Name == "Engineering").DepartmentID,
  81:                    Instructors = new List<Instructor>() 
  82:                  },
  83:                  new Course {CourseID = 4022, Title = "Microeconomics", Credits = 3,
  84:                    DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
  85:                    Instructors = new List<Instructor>() 
  86:                  },
  87:                  new Course {CourseID = 4041, Title = "Macroeconomics", Credits = 3,
  88:                    DepartmentID = departments.Single( s => s.Name == "Economics").DepartmentID,
  89:                    Instructors = new List<Instructor>() 
  90:                  },
  91:                  new Course {CourseID = 1045, Title = "Calculus",       Credits = 4,
  92:                    DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
  93:                    Instructors = new List<Instructor>() 
  94:                  },
  95:                  new Course {CourseID = 3141, Title = "Trigonometry",   Credits = 4,
  96:                    DepartmentID = departments.Single( s => s.Name == "Mathematics").DepartmentID,
  97:                    Instructors = new List<Instructor>() 
  98:                  },
  99:                  new Course {CourseID = 2021, Title = "Composition",    Credits = 3,
 100:                    DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
 101:                    Instructors = new List<Instructor>() 
 102:                  },
 103:                  new Course {CourseID = 2042, Title = "Literature",     Credits = 4,
 104:                    DepartmentID = departments.Single( s => s.Name == "English").DepartmentID,
 105:                    Instructors = new List<Instructor>() 
 106:                  },
 107:              };
 108:           courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
 109:           context.SaveChanges();
 110:   
 111:           var officeAssignments = new List<OfficeAssignment>
 112:              {
 113:                  new OfficeAssignment { 
 114:                      InstructorID = instructors.Single( i => i.LastName == "Fakhouri").InstructorID, 
 115:                      Location = "Smith 17" },
 116:                  new OfficeAssignment { 
 117:                      InstructorID = instructors.Single( i => i.LastName == "Harui").InstructorID, 
 118:                      Location = "Gowan 27" },
 119:                  new OfficeAssignment { 
 120:                      InstructorID = instructors.Single( i => i.LastName == "Kapoor").InstructorID, 
 121:                      Location = "Thompson 304" },
 122:              };
 123:           officeAssignments.ForEach(s => context.OfficeAssignments.AddOrUpdate(p => p.Location, s));
 124:           context.SaveChanges();
 125:   
 126:           AddOrUpdateInstructor(context, "Chemistry", "Kapoor");
 127:           AddOrUpdateInstructor(context, "Chemistry", "Harui");
 128:           AddOrUpdateInstructor(context, "Microeconomics", "Zheng");
 129:           AddOrUpdateInstructor(context, "Macroeconomics", "Zheng");
 130:   
 131:           AddOrUpdateInstructor(context, "Calculus", "Fakhouri");
 132:           AddOrUpdateInstructor(context, "Trigonometry", "Harui");
 133:           AddOrUpdateInstructor(context, "Composition", "Abercrombie");
 134:           AddOrUpdateInstructor(context, "Literature", "Abercrombie");
 135:   
 136:           context.SaveChanges();
 137:   
 138:           var enrollments = new List<Enrollment>
 139:              {
 140:                  new Enrollment { 
 141:                      StudentID = students.Single(s => s.LastName == "Alexander").StudentID, 
 142:                      CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID, 
 143:                      Grade = Grade.A 
 144:                  },
 145:                   new Enrollment { 
 146:                      StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
 147:                      CourseID = courses.Single(c => c.Title == "Microeconomics" ).CourseID, 
 148:                      Grade = Grade.C 
 149:                   },                            
 150:                   new Enrollment { 
 151:                      StudentID = students.Single(s => s.LastName == "Alexander").StudentID,
 152:                      CourseID = courses.Single(c => c.Title == "Macroeconomics" ).CourseID, 
 153:                      Grade = Grade.B
 154:                   },
 155:                   new Enrollment { 
 156:                       StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
 157:                      CourseID = courses.Single(c => c.Title == "Calculus" ).CourseID, 
 158:                      Grade = Grade.B 
 159:                   },
 160:                   new Enrollment { 
 161:                       StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
 162:                      CourseID = courses.Single(c => c.Title == "Trigonometry" ).CourseID, 
 163:                      Grade = Grade.B 
 164:                   },
 165:                   new Enrollment {
 166:                      StudentID = students.Single(s => s.LastName == "Alonso").StudentID,
 167:                      CourseID = courses.Single(c => c.Title == "Composition" ).CourseID, 
 168:                      Grade = Grade.B 
 169:                   },
 170:                   new Enrollment { 
 171:                      StudentID = students.Single(s => s.LastName == "Anand").StudentID,
 172:                      CourseID = courses.Single(c => c.Title == "Chemistry" ).CourseID
 173:                   },
 174:                   new Enrollment { 
 175:                      StudentID = students.Single(s => s.LastName == "Anand").StudentID,
 176:                      CourseID = courses.Single(c => c.Title == "Microeconomics").CourseID,
 177:                      Grade = Grade.B         
 178:                   },
 179:                  new Enrollment { 
 180:                      StudentID = students.Single(s => s.LastName == "Barzdukas").StudentID,
 181:                      CourseID = courses.Single(c => c.Title == "Chemistry").CourseID,
 182:                      Grade = Grade.B         
 183:                   },
 184:                   new Enrollment { 
 185:                      StudentID = students.Single(s => s.LastName == "Li").StudentID,
 186:                      CourseID = courses.Single(c => c.Title == "Composition").CourseID,
 187:                      Grade = Grade.B         
 188:                   },
 189:                   new Enrollment { 
 190:                      StudentID = students.Single(s => s.LastName == "Justice").StudentID,
 191:                      CourseID = courses.Single(c => c.Title == "Literature").CourseID,
 192:                      Grade = Grade.B         
 193:                   }
 194:              };
 195:   
 196:           foreach (Enrollment e in enrollments)
 197:           {
 198:              var enrollmentInDataBase = context.Enrollments.Where(
 199:                  s =>
 200:                       s.Student.StudentID == e.StudentID &&
 201:                       s.Course.CourseID == e.CourseID).SingleOrDefault();
 202:              if (enrollmentInDataBase == null)
 203:              {
 204:                 context.Enrollments.Add(e);
 205:              }
 206:           }
 207:           context.SaveChanges();
 208:        }
 209:   
 210:        void AddOrUpdateInstructor(SchoolContext context, string courseTitle, string instructorName)
 211:        {
 212:           var crs = context.Courses.SingleOrDefault(c => c.Title == courseTitle);
 213:           var inst = crs.Instructors.SingleOrDefault(i => i.LastName == instructorName);
 214:           if (inst == null)
 215:              crs.Instructors.Add(context.Instructors.Single(i => i.LastName == instructorName));
 216:        }
 217:     }
 218:  }

As you saw in the first tutorial, most of this code simply updates or creates new entity objects and loads sample data into properties as required for testing. However, notice how the Course entity, which has a many-to-many relationship with the Instructor entity, is handled:

[!code-csharpMain]

   1:  var courses = new List<Course>
   2:  {
   3:       new Course {CourseID = 1050, Title = "Chemistry",      Credits = 3,
   4:         Department = departments.Single( s => s.Name == "Engineering"),
   5:         Instructors = new List<Instructor>() 
   6:       },
   7:       ...
   8:  };
   9:  courses.ForEach(s => context.Courses.AddOrUpdate(p => p.CourseID, s));
  10:  context.SaveChanges();

When you create a Course object, you initialize the Instructors navigation property as an empty collection using the code Instructors = new List<Instructor>(). This makes it possible to add Instructor entities that are related to this Course by using the Instructors.Add method. If you didn’t create an empty list, you wouldn’t be able to add these relationships, because the Instructors property would be null and wouldn’t have an Add method. You could also add the list initialization to the constructor.

Add a Migration and Update the Database

From the PMC, enter the add-migration command:

PM> add-Migration Chap4

If you try to update the database at this point, you’ll get the following error:

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

Edit the <timestamp>_Chap4.cs file, and make the following code changes (you’ll add a SQL statement and modify an AddColumn statement):

[!code-csharpMain]

   1:  CreateTable(
   2:          "dbo.CourseInstructor",
   3:          c => new
   4:              {
   5:                  CourseID = c.Int(nullable: false),
   6:                  InstructorID = c.Int(nullable: false),
   7:              })
   8:          .PrimaryKey(t => new { t.CourseID, t.InstructorID })
   9:          .ForeignKey("dbo.Course", t => t.CourseID, cascadeDelete: true)
  10:          .ForeignKey("dbo.Instructor", t => t.InstructorID, cascadeDelete: true)
  11:          .Index(t => t.CourseID)
  12:          .Index(t => t.InstructorID);
  13:   
  14:      // Create  a department for course to point to.
  15:      Sql("INSERT INTO dbo.Department (Name, Budget, StartDate) VALUES ('Temp', 0.00, GETDATE())");
  16:      //  default value for FK points to department created above.
  17:      AddColumn("dbo.Course", "DepartmentID", c => c.Int(nullable: false, defaultValue: 1)); 
  18:      //AddColumn("dbo.Course", "DepartmentID", c => c.Int(nullable: false));
  19:   
  20:      AlterColumn("dbo.Course", "Title", c => c.String(maxLength: 50));
  21:      AddForeignKey("dbo.Course", "DepartmentID", "dbo.Department", "DepartmentID", cascadeDelete: true);
  22:      CreateIndex("dbo.Course", "DepartmentID");
  23:  }
  24:   
  25:  public override void Down()
  26:  {

(Make sure that you comment out or delete the existing AddColumn line when you add the new one, or you’ll get an error when you enter the update-database command.)

Sometimes when you execute migrations with existing data, you need to insert stub data into the database to satisfy foreign key constraints, and that’s what you’re doing now. The generated code adds a non-nullable DepartmentID foreign key to the Course table. If there are already rows in the Course table when the code runs, the AddColumn operation would fail because SQL Server doesn’t know what value to put in the column that can’t be null. Therefore you’ve changed the code to give the new column a default value, and you’ve created a stub department named “Temp” to act as the default department. As a result, if there are existing Course rows when this code runs, they will all be related to the “Temp” department.

When the Seed method runs, it will insert rows in the Department table and it will relate existing Course rows to those new Department rows. If you haven’t added any courses in the UI, you would then no longer need the “Temp” department or the default value on the Course.DepartmentID column. To allow for the possibility that someone might have added courses by using the application, you’d also want to update the Seed method code to ensure that all Course rows (not just the ones inserted by earlier runs of the Seed method) have valid DepartmentID values before you remove the default value from the column and delete the “Temp” department.

After you have finished editing the <timestamp>_Chap4.cs file, enter the update-database command in the PMC to execute the migration.

[!NOTE] It’s possible to get other errors when migrating data and making schema changes. If you get migration errors you can’t resolve, you can either change the connection string in the Web.config file or delete the database. The simplest approach is to rename the database in Web.config file. For example, change the database name to CU_test as shown in the following:

[!code-xmlMain]

   1:  <add name="SchoolContext" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=CU_Test;
   2:        Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\CU_Test.mdf" 
   3:        providerName="System.Data.SqlClient" />

With a new database, there is no data to migrate, and the update-database command is much more likely to complete without errors. For instructions on how to delete the database, see How to Drop a Database from Visual Studio 2012.

Open the database in Server Explorer as you did earlier, and expand the Tables node to see that all of the tables have been created. (If you still have Server Explorer open from the earlier time, click the Refresh button.)

You didn’t create a model class for the CourseInstructor table. As explained earlier, this is a join table for the many-to-many relationship between the Instructor and Course entities.

Right-click the CourseInstructor table and select Show Table Data to verify that it has data in it as a result of the Instructor entities you added to the Course.Instructors navigation property.

Table_data_in_CourseInstructor_table
Table_data_in_CourseInstructor_table

Summary

You now have a more complex data model and corresponding database. In the following tutorial you’ll learn more about different ways to access related data.

Links to other Entity Framework resources can be found in the ASP.NET Data Access Content Map.

Previous Next



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/mvc/overview/older-versions/getting-started-with-ef-5-using-mvc-4/creating-a-more-complex-data-model-for-an-asp-net-mvc-application.htm
< THANKS ME>