Define Custom Code-First Conventions in EF 6:

You learn 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.

Configuration Conventions:

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 the Fluent API.

For example, you want to configure a property as a key property whose name matches with {entity name}_ID e.g. Student_ID property of 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);
}

The same way, you can define a convention for the size of a data type.

The following defines 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 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 custom convention class, add it in the conventions as shown below:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Conventions.Add<PKConvention>();
}

Model Conventions:

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 implement IStoreModelConvention for SSDL convention.

Visit Custom Convention in EF 6 for more information.


Test Your Entity Framework Knowledge: