Custom Conventions
Code First includes a set of simple, model-wide behaviors that provide sensible configuration defaults for the parts of your model that have not been explicitly configured using Data Annotations or the Fluent API. These default behaviors are referred to as Conventions. One commonly requested feature is the ability to add your own conventions.The Custom Conventions feature will let you define your own conventions to provide custom configuration defaults for your model. The heart of this new feature is the conventions interfaces that you use to implement your own custom conventions. These interfaces fall into two main categories: Configuration-based and Model-based.
Configuration-based conventions
The first type of convention is based on reflection and configuration objects and can be created using IConfigurationConvention. The configuration objects used by this type of convention are similar to the Fluent API objects that are typically used when overriding DbContext.OnModelCreating().class DefaultDateTimeColumnTypeConvention : IConfigurationConvention<PropertyInfo, DateTimePropertyConfiguration> { public void Apply( PropertyInfo propertyInfo, Func<DateTimePropertyConfiguration> configuration) { if (configuration().ColumnType == null) { configuration().ColumnType = "datetime2"; } } }
- Type
- PropertyInfo
- ModelConfiguration
- PropertyConfiguration
- NavigationPropertyConfiguration
- PrimitivePropertyConfiguration
- DateTimePropertyConfiguration
- DecimalPropertyConfiguration
- LengthPropertyConfiguration
- BinaryPropertyConfiguration
- StringPropertyConfiguration
- StructuralTypeConfiguration
- ComplexTypeConfiguration
- EntityTypeConfiguration
Model-based conventions
The second type of convention is based on the underlying model metadata. The interfaces used to create these conventions are IEdmConvention, IDbConvention & IDbMappingConvention. This type of convention gives you more control than configuration-based conventions because it allow you to directly manipulate the model metadata that gets used by Entity Framework.Note: Additional work is also being done to consolidate and improve the model metadata API used by these conventions. For more information, see Work Item 555.
class DefaultDecimalScaleConvention : IEdmConvention<EdmProperty> { public void Apply(EdmProperty property, EdmModel model) { if (property.PropertyType.PrimitiveType == EdmPrimitiveType.Decimal && property.PropertyType.PrimitiveTypeFacets.Scale == null) { property.PropertyType.PrimitiveTypeFacets.Scale = 4; } } }
- IEdmConvention
- IDbConvention
- IDbMappingConvention
Adding conventions
To enable a custom convention to be applied during model creation, call Add() on DbModelBuilder.Conventions.protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add<DefaultDateTimeColumnTypeConvention>(); }
modelBuilder.Conventions.AddBefore<DecimalPropertyConvention>(
new DefaultDecimalScaleConvention());