Thursday, 15 November 2012

Some Notes about Entity Framework Code First Fluent API on Properties

- By convention a property with name 'Id' or '[Class]Id' will become the generated table primary key.

- string property will become an nvarchar(max) column.

- Keys properties and value types (any numeric, DateTime, bool and char) properties will become non-nullable columns. Reference types (String and arrays) and nullable value types (e.g.; Int16?, int?, decimal?, etc) properties will yield as nullable columns.

- byte[] property will become varbinary(max) column.

- Configuring primary key
modelBuilder.Entity<[ClassName]>().HasKey(p => p.[PropertyName]);

- Non-nullable column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsRequired();

- Nullable column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsOptional();

- Set the maximum length for a property and the generated column
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).HasMaxLength([NumberLength]);

- Largest possible length of column's data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsMaxLength();

- Use fixed rather than variable data type, e.g.; varchar instead of nvarchar
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsFixedLength();
To extend the fixed data type column use
.IsFixedLength().HasMaxLength([NumberLength])
To have largest possible length of the fixed data type column use
.IsFixedLength().IsMaxLength()
For string property, we can change the default data type generated (nvarchar) to varchar by using
.IsUnicode(false)

- Use variable length data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsVariableLength();

- Specify the generated column data type
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).HasColumnType("[ColumnName]");

- Set the property to be used for concurrency checking
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsConcurrencyToken();

- Set a row version column in the generated table to be used as the concurrency token
modelBuilder.Entity<[ClassName]>().Property(p => p.[PropertyName]).IsRowVersion();
The property must have Byte[] type. IsRowVersion() is only allowed one in a class.


Further reading:
Configuring Properties and Types with the Fluent API

No comments: