2

I am new to Entity Framework and am about to embark on a new ASP.NET MVC project using EF5 Code First.

As I understand it, you can either use Data Annotations against the properties within your Domain Model objects, or you can use a Fluent API, to define the properties data type (in the DB when the objects are created), size, whether they are nullable and so on.

Is there a general recommended approach as to which to go with?

I couldn't see how when using Data Annotations, I can specify the datatype and size for that property when it's created in the DB, whereas with the Fluent API it looks like you can do the following:

Property(g => g.ModelName).HasColumnType("varchar");
Property(g => g.ModelName).HasMaxLength(100);
Property(g => g.ModelName).IsRequired();

When using Data Annotations, by default it appears to be using nvarchar(MAX) for all my string properties for example.

Is there a way to do the above using Data Annotations? Does it offer the same degree of 'tweaking' as Fluent API or should I be leaving the domain model alone and separate all of this 'tweaking' to separate Fluent API classes for each domain model object?

marcusstarnes
  • 6,393
  • 14
  • 65
  • 112

1 Answers1

3

I would recommend the fluent API. Data annotations are a subset, and don't for example include cascading delete for relationships.

Also, you may consider polluting your models with persistence logic such as database column names inappropriate.

devdigital
  • 34,151
  • 9
  • 98
  • 120
  • [more info](http://stackoverflow.com/questions/5354900/code-first-are-data-annotations-or-the-fluent-api-better) . Do you know if the fluent API now (Dec 2013) works with MVC validation similar to how Data Annotations do? – subsci Dec 14 '13 at 21:44
  • Difficult to keep up with changing features and API... [fluent api validation](http://msdn.microsoft.com/en-us/data/gg193959.aspx) – subsci Dec 14 '13 at 21:52