Customizing schema generation when using Code First with Entity Framework

In my previous post I generated a database without any mapping or customization, I got what Entity Framework could coerce from my class. Look at the schema which was generated.

generated table schema

Let’s see what I did not like about this.

  • table name is not what I like to have
  • Id was not marked as identity column, so no auto generation for this column
  • all alphanumeric columns are created using nvarchar(MAX) which is not good too
  • and the last, I wanted to use only date for birthdate not datetime

So how to make these tweaks. I found two different ways of doing this, one was to decorate your class and properties with attributes. That was not a good option for me, as I wanted to decorate them differently, and secondly I try to avoid these decoration. Second option was to use fluent configuration API for that purpose. Actually I liked the idea, as I have used similar things with NHibernate previously.

This involves three steps

  • create a class which inherits from EntityTypeConfiguration<T>, where T is the class you need to configure
  • second you need to make appropriate configurations, code is given below
  • and finally tell your context which mapping to use

Here is PersonItemConfiguration class for that purpose.

Lets try to digest what all these options are

  • ToTable: which table to map this entity with
  • HasKey: which property should be treated as primary key, if any table has more than one column as primary key then you will have to pass all those properties in an array
  • Property: customize the field mapping using this. You can specify the column name, underlying data type, length in case of alphanumeric field, whether optional or required, and what value generation scheme to use (none, computed, or identity)

There are different types of property configuration schemes available, I will discuss them separately. And that’s how it is integrated with your context.

After executing the test which we had previously created, we get the following schema.

modified schema layout

As you see here, I was able to generate schema as I required. This technique will help when we already have a schema and need to map our entities with that schema.

Quite interesting and imaginative?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.