Click here to Skip to main content
15,887,683 members
Articles / Programming Languages / C#

Using the Code First Model Configuration Classes

Rate me:
Please Sign up or sign in to vote.
4.00/5 (7 votes)
7 Mar 2011CPOL2 min read 82.4K   7   2
Aother model configuration option which is built inside Code First.

Introduction

In the past, I explained how to use the Code First Fluent API in order to configure and shapeUsing Code First Model Configurations Classes your EDM during runtime. One of the problems that might arise when you use the Fluent API as I showed in the previous post is that the OnModelCreating method might become bloated and hard to read. This is the time to get familiar with another model configuration option which is built inside Code First.

Model Configurations Classes

When you use Code First, you will probably configure the creation of the model in some way. You can use the Code First Fluent API in order to do that. When you use the Fluent API, the place that you will use it is the OnModelCreating method in the DbContext class. In very big models, that might be a problem. Quickly, you will find yourself having a very big and bloated method which holds all the configurations. This is the time for refactoring your code to use model configurations. There are two major classes that you will use: the generic EntityTypeConfiguration and ComplexTypeConfiguration. Both of the classes live in the System.Data.Entity.ModelConfiguration assembly.

Usage Example

Let's revisit the DbContext from the previous post:

C#
public class SchoolEntities : DbContext
{
  #region Ctor 

  public SchoolEntities() :
    base("MySchool")
  {
  }

  #endregion

  #region Properties

  public DbSet<Course> Courses { get; set; }
  public DbSet<Department> Departments { get; set; }

  #endregion

  #region Methods

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Department>().
      Property(d => d.Name).
      IsRequired().
      HasMaxLength(50);

    modelBuilder.Entity<Department>().
      Property(d => d.DepartmentID).
      HasDatabaseGenerationOption(DatabaseGenerationOption.None);

    modelBuilder.Entity<Department>().
      HasMany(d => d.Courses).
      WithRequired(c => c.Department).
      HasForeignKey(c => c.DepartmentID).
      WillCascadeOnDelete();

    modelBuilder.Entity<Department>().
      Ignore(d => d.Administrator);

    modelBuilder.Entity<Course>().
      Property(c => c.Title).
      IsRequired().
      HasColumnName("Name");      
  }    

  #endregion
}

If I want to use the EntityTypeConfiguration, I’ll create a new class for the Department configuration. The class will inherit from EntityTypeConfiguration<Department> and in its constructor, I’ll use the Fluent API for configurations. The following code sample shows the DepartmentTypeConfiguration class:

C#
public class DepartmentTypeConfiguration : EntityTypeConfiguration<Department>
{
  #region Ctor

  public DepartmentTypeConfiguration()
  {
    Property(d => d.Name).
      IsRequired().
      HasMaxLength(50);

    Property(d => d.DepartmentID).
      HasDatabaseGenerationOption(DatabaseGenerationOption.None);

    HasMany(d => d.Courses).
      WithRequired(c => c.Department).
      HasForeignKey(c => c.DepartmentID).
      WillCascadeOnDelete();

    Ignore(d => d.Administrator);
  }

  #endregion
}

Now that we have the class, we will wire it into the ModelBuilder by using the Add method of its Configuration collection. The following code sample shows you how to do that:

C#
public class SchoolEntities : DbContext
{
  #region Ctor

  public SchoolEntities() :
    base("MySchool")
  {
  }

  #endregion

  #region Properties

  public DbSet<Course> Courses { get; set; }
  public DbSet<Department> Departments { get; set; }

  #endregion

  #region Methods

  protected override void OnModelCreating(ModelBuilder modelBuilder)
  {
    base.OnModelCreating(modelBuilder);

    modelBuilder.Configurations.Add(new DepartmentTypeConfiguration());

    modelBuilder.Entity<Course>().
      Property(c => c.Title).
      IsRequired().
      HasColumnName("Name");
  }

  #endregion
}

During runtime, we will get the same EDM whether we use the first method with the configurations inside the OnModelCreating method or the second method of EntityTypeConfiguration.

Summary

When you use Code First, you get a lot of configuration options. If your model is small, you can create all the configurations inside the OnModelCreating method. When the model starts to grow, you can use the ModelConfiguration classes in order to divide your implementation to small objects with configuration responsibility.

This article was originally posted at http://feeds.feedburner.com/GilFinkBlog

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead sparXys
Israel Israel
Gil Fink is a web development expert and ASP.Net/IIS Microsoft MVP. He is the founder and owner of sparXys. He is currently consulting for various enterprises and companies, where he helps to develop Web and RIA-based solutions. He conducts lectures and workshops for individuals and enterprises who want to specialize in infrastructure and web development. He is also co-author of several Microsoft Official Courses (MOCs) and training kits, co-author of "Pro Single Page Application Development" book (Apress) and the founder of Front-End.IL Meetup. You can read his publications at his website: http://www.gilfink.net

Comments and Discussions

 
GeneralJust what I needed Pin
Damon Jordan21-Oct-11 3:36
Damon Jordan21-Oct-11 3:36 
GeneralGenerate this code Pin
Christopher R Davis14-Mar-11 9:23
Christopher R Davis14-Mar-11 9:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.