Entity Mapping using EntityTypeConfiguration

In Entity Framework there are two ways to map an entity to a database table,

  1. Using Attributes
  2. Using the EntityTypeConfiguration class

I prefer the second approach as it gives the following benefits,

  • The entity does not get polluted with attributes
  • The mapping can be grouped in a separate namespace and can also be put in a different assembly

Lets see how this is done!

Lets assume the following entity

    public class Product{
        public int Id { get; set; }
        public string Name { get; set; }

Create a mapping class

    public class ProductMap : EntityTypeConfiguration<Product>{
        public ProductMap(){



Tell EntityFramework about this mapping

    public class TestDbContext : DbContext{
        protected override void OnModelCreating(DbModelBuilder modelBuilder){