Over a million developers have joined DZone.

Entity Framework 5 First Steps – Mapping

DZone's Guide to

Entity Framework 5 First Steps – Mapping

· ·
Free Resource

In a previous article, I’ve explained how simple it is to use EF5 to access a database and use Database-Migrations to create a database suitable to contain your entities (with a simple Update-Command from the package manager console). When you show this technique to many programmers, the first complaint they have is, “The structure of the generated tables is not suitable to me.”


Figure 1: Database generated with previous code example

Suppose you want to specify a maximum length for the various columns, specify not-null columns, and you want them to be named with a convention. Finally, you don't want to use identity columns, because all the customers you will save in this database come from a legacy CMR application and you want to be able to use the very same id of the CRM system.

If you want to customize how the table is generated, but you want to be completely free on how you name entities, properties, or context dbSet, you need to specify a custom mapping that does not use standard convention over configuration. First you must create a mapping class for your Customer class (you can also do this with Attributes) to specify how properties will be mapped on database tables and columns.

public class CustomerMap : EntityTypeConfiguration<Customer>
    public CustomerMap()
        // Primary Key
        this.HasKey(t => t.Id);
        // Properties
        // Table & Column Mappings
        this.Property(t => t.Id)
        this.Property(t => t.Name)
        this.Property(t => t.Address)

You can put this class wherever you want, I usually put it into a subfolder named Mappings and I usually call this class with the same name of the entity with the suffix Map. Now you should only specify in your DbContext that this mapping is available.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    modelBuilder.Configurations.Add(new CustomerMap());

By overriding OnModelCreating you can add your custom mapping to the Configurations collection, now if you issue another Update-Database you can verify that the table is now created the way you want.


Figure 2: New structure of the table that respect the CustomerMap class

Now you can see that the table is called Customer, columns are named with your convention and length and not null are created correctly. This is really good because if the DBA or some convention impose you some naming rules on database tables and column you are free to use business-friendly names in your entities.



Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}