Entity framework 6 and fluent mapping

If you google for EF and fluent mapping this is the first hit you get which is not strange since its the official MSDN page about fluent mapping in EF6.

They only discuss overriding the OnModelCreating method and configure the mapping inline in that method. And this is the most common way of dealing with fluent mapping out there in the community. But there is a much better and seperated way of doing it which MSDN fail to show.

System.Data.Entity.ModelConfiguration.EntityTypeConfiguration

This little class is your salvation when working with Fluent mapping in large enterprise systems. Implement it like.

public class FooConfiguration : EntityTypeConfiguration<Foo>
{
	public FooConfiguration()
	{
		HasKey(t => t.Id);

		Property(t => t.Name)
			.HasMaxLength(100)
			.IsRequired();

		ToTable("Foo","FooSchema"); 
			
	}
}

Add it from the OnModelCreating method in your derived DbContext

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
	modelBuilder.Configurations.Add(new FooConfiguration());
}

Or you can add all Configurations for an Assembly

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
	modelBuilder.Configurations.AddFromAssembly(this.GetType().Assembly);
}

Oh, and while your at it, stop doing

using(var contxt = new MyContext()) {}

Let the IoC lifetime manage the context for you!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s