You learned about code-first conventions in the previous chapter. EF 6 also provides the ability to define your own custom conventions which will be the default behavior for your models.
There are two main types of Conventions, Configuration Conventions and Model Conventions.
A Configuration Convention is a way to configure entities without overriding the default behavior provided in the Fluent API.
You can define a configuration convention in the OnModelCreating()
method and also in a custom class, similar to how you would define normal entity mappings with Fluent API.
For example, you want to configure a property as a key property whose name matches with the {entity name}_ID e.g., the Student_ID
property of the Student
entity will be primary key. The following defines this convention.
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder .Properties() .Where(p => p.Name == p.DeclaringType.Name + "_ID") .Configure(p => p.IsKey()); base.OnModelCreating(modelBuilder); }
In the same way, you can define a convention for the size of a data type.
The following defines a convention for string properties. It will create nvarchar
columns with size 50 in SQL Server for all string type properties of an entity.
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder .Properties() .Where(p => p.PropertyType.Name == "String") .Configure(p => p.HasMaxLength(50)); base.OnModelCreating(modelBuilder); }
You can also define a custom class for this convention by deriving the Convention
class, as shown below:
public class PKConvention : Convention { public PKConvention() { .Properties() .Where(p => p.Name == p.DeclaringType.Name + "_ID") .Configure(p => p.IsKey()); } }
After creating a custom convention class, add it in the conventions as shown below:
protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Add<PKConvention>(); }
Model Conventions are based on the underlying model metadata. There are conventions for both CSDL and SSDL. Create a class that implements IConceptualModelConvention
from CSDL conventions and IStoreModelConvention
from SSDL conventions.
Visit Custom Convention in EF 6 for more information.