Returning to my topic of Entity Framework, today I want to compare the Decoration technique of defining classes as discussed yesterday with the fluent syntax technique.
Classes used to communicate with tables through Entity Framework may be more fully defined using fluent syntax in a Model Builder than with decorations. Using fluid syntax you can define all of the options available in decorations, and many additional optoins not available through decorations.
The fluid configuration makes sense to me when defining a class to communicate correctly with the database. The class entities are further defined in your DbContext class using the MigrationBuilder helper class. Here’s a code sample to clarify:
public class DrawingContext : DbContext
{
public DbSet<Color> Colors { set; get; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Color>()
.Property(e => e.Name)
.IsRequired()
.IsUnicode(false)
.HasMaxLength(128)
.IsVariableLength();
}
}
A DbContext is created by inheriting from DbContext. In the DbContext (DrawingContext in my example) I define a DbSet for my Color class. Then, in the OnModelCreating event I create an override method implementing my configuration wishes using Fluent syntax.
Notice that I am able to create a number of behaviors on the Name property of my Color class. I tell EF that this property when communicating with SQL Server (My data source) that the name is required, not Unicode (ex. Uses varchar instead of nvarchar), has a max character length of 128, and is a variable length data type.
This is translated into
ALTER TABLE Colors ADD Name VARCHAR(128) NOT NULL
There are many more settings I can implement through the fluid syntax.
One good tutorial I watched today used both decorations and fluent syntax for their models. They used a model to communicate with EF, fully annotated through fluid syntax. Then they used a ViewModel, usually with the same definition as the data model, to communicate with the presentation layer. The ViewModel was highly decorated, enabling validation and many other good things when working with the gui.
I found this to be a preferred, for me anyway, implementation. Yes, it required an additional class. But the ViewModel classes did not always map one-to-one with the data classes. At some point you’re probably going to have some adaption anyway, to keep your business classes clean, and not require them to be exactly like your data structure. It’s even more likely you have differences in ViewModels and DataModels in legacy database systems,
Here’s a good link using EF 5 to demonstrate this technique in more detail: Creating a More Complex Data Model.
The point is, you can still use EF and maintain a clean separation of presentation, validation, and ORM conversion.
Cheers,
Ben