Click here to Skip to main content
Click here to Skip to main content

EF Feature CTP5 – Code First Fluent API

By , 8 Dec 2010
 

One of Code First main features is the Fluent API. This API can help you to configure the model in order to shape it (and the database) better. In this post I’m going to show a simple example for how to use the Fluent API. Pay attention that the details I provide might change in the future since its only a CTP and not a release.

The Example Model

In the example I’m going to use the following model:

public class SchoolEntities : DbContext
{
  #region Properties
 
  public DbSet<Course> Courses { get; set; }
  public DbSet<Department> Departments { get; set; }
 
  #endregion
 
  #region Methods
 
  protected override void OnModelCreating(
    System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
  {
    base.OnModelCreating(modelBuilder);
 
    // put here the fluent code
  }
 
  #endregion
}
 
public partial class Course
{
  #region Properties
 
  public int CourseID { get; set; }
  public string Title { get; set; }
  public string Days { get; set; }
  public DateTime Time { get; set; }
  public string Location { get; set; }
  public int Credits { get; set; }
  public int DepartmentID { get; set; }
 
  public virtual Department Department { get; set; }
 
  #endregion
}
 
public class Department
{
  #region Properties
 
  public int DepartmentID { get; set; }
  public string Name { get; set; }
  public decimal Budget { get; set; }
  public DateTime StartDate { get; set; }
  public int Administrator { get; set; }
 
  public virtual ICollection<Course> Courses { get; set; }
 
  #endregion
}

Fluent API Example

After you create your model there are a lot of ways to configure the model using the Fluent API. The main place to do that is in the OnModelCreatingmethod which you override in the DbContext That method gets a ModelBuilderinstance which can be used to configure the model. The following example shows how to write some configuration with the API:

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");      
}

What is Configured?

Lets explain what you see in the above code. When I want to configure an entity I use the Entity method with the entity as a generic parameter. Then I’m exposed to the Fluent API and can start configure my model. In the first line I configure the Name property of the department as required and with length of no more than 50 characters. In the second line I configure the DepartmentID as non database generated (since by default all the ID will be database generated). The third line creates a one to many relation between the department and its course collection. You first use the HasMany to indicate the many side and then use the WithRequired to indicate the one side of the relation. The HasForeignKey indicate the foreign key on the many side. The last method, WillCascadeOnDelete, will add cascade delete on the entity graph. The forth line will force the model to ignore the administrator property of the department and therefore it won’t be generated in the database. The fifth line indicates that the Title property is required and that in the database the column name will be Name instead of Title. Here is a simple example of creating data and inserting it to the database:

class Program
{
  static void Main(string[] args)
  {
    using (SchoolEntities context = new SchoolEntities())
    {
      var department = new Department
      {
        DepartmentID = 1,
        Administrator = 2,
        Budget = 100000,
        Name = "Data Access",
        StartDate = DateTime.Now
      };
      var course = new Course
      {
        Credits = 2,
        Days = "MF",
        Location = "Class 1",
        Time = DateTime.Now,
        Title = "Entity Framework",
        Department = department,
      };
      context.Departments.Add(department);
      context.SaveChanges();
    }
  }
}

Running this example will generate a new database by the name ClassLibrary1.SchoolEntities with all the configurations that were written in the OnModelCreatingmethod. If you want to change the generated database name (which is taken from the namespace and context name by default) you need to create a constructor to the DbContextwith a call for the base constructor that gets a string as parameter:

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

The resulting database:

Database

Summary

Lets sum up, Code First has a very interesting feature of fluent API. The fluent API for model configuration is easy to understand and use. In this post I showed and explain a small portion of the API.

License

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

About the Author

Gil Fink
Architect Sela Group
Israel Israel
Member
Gil Fink is an expert in ASP.NET and Microsoft data platform and serves as a Senior Architect at SELA Group. He is a Microsoft data platform MVP and a certified MCPD Enterprise Application Developer. Gil has worked in the past in variety of positions and projects as a leading developer, team leader, consultant and more. His interests include Entity Framework, Enterprise Library, WCF, LINQ, ADO.NET and many other new technologies from Microsoft.
 

My technical blog: http://www.gilfink.net

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberMember 236415010 Mar '11 - 21:21 
After many many hours of searching, this is the only article I found that explained how to use relationships from beginning to end. I am extremely grateful to the author. Thankyou.

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

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 8 Dec 2010
Article Copyright 2010 by Gil Fink
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid