Entity Framework using Fluent API and Code First in ASP.NET MVC

I have been playing with EF Code First in ASP.NET MVC Web Applications. Up until now I have mainly been using Data Annotation Attributes on the model classes to help EF properly map those classes to tables in a SQL Server Database when using EF Code First. The Book Class I mentioned in the post, MvcScaffolding Nuget Package and EF Code First - Code Generation, is a good example of using the Data Annotations Attributes:

 

EF Code First Data Annotations

 

The immediate benefit of using Data Annotations as a declarative way to map EF Classes is that ASP.NET MVC supports Data Annotations for validation, too, which means if you have a simple ASP.NET MVC Web Application where you are binding Model Classes in the Controllers, you get your validation and your database mapping together using Data Annotations.

This is quite attractive, but if Data Annotations is not ideal to you, one also has the option of using the EF Fluent API. Once can model Book as shown below. Notice I override the OnModelCreating Method of DbContext and then use DbModelBuilder to specify various options, like HasKey, IsRequired, HasMaxLength, etc.

 

EF Code First Fluent API

 

It certainly is nice to have options for both Data Annotations and a Fluent API when using EF Code First. I recommend trying both to see which one you like better.

 

David Hayden

 

Related Posts:

 

posted on Tuesday, April 26, 2011 8:53 AM

Main

David Hayden Google +

David Hayden Twitter

Health & Fitness

JavaScript Patterns Book Review

HTML 5 and CSS3 - Develop with Tomorrow's Standards Today

Professional ASP.NET Design Patterns Book Review

Beginning Mac Programming Book Review

C# in Depth Book Review

ASP.NET MVC

Orchard CMS

Categories