Click here to Skip to main content
Click here to Skip to main content
Go to top

Using the Code First Model Configuration Classes

, 7 Mar 2011
Rate this:
Please Sign up or sign in to vote.
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:

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:

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:

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.

License

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

Share

About the Author

Gil Fink
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
Follow on   Twitter   Google+   LinkedIn

Comments and Discussions

 
GeneralJust what I needed PinmemberDamon Jordan21-Oct-11 3:36 
GeneralGenerate this code PinmemberChristopher R Davis14-Mar-11 9:23 

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 7 Mar 2011
Article Copyright 2011 by Gil Fink
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid