Custom Code-first Conventions:
Code-first have a set of default behaviors for the models is referred to as conventions. EF 6 provides the ability to define your own custom conventions which would be the default behavior for your models.
There is both main types of conventions, Configuration conventions and Model conventions.
Configuration Conventions:
Configuration conventions is a-configure entities without overriding the default behavior provided in the Fluent a Pi. You can define a configuration convention inside your onmodelcreating event or in a custom convention Class, similar to Ho W would define normal entity mappings with the Fluent API.
For the example, you can define a primary key of an entity which has the property named {entity name} _id, e.g. student_id of Student entity would be primary key:
protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) { modelBuilder . Properties () "_id") = p.iskey ()); Base . Onmodelcreating (ModelBuilder);}
The following example shows how to set the string length of the Description property in all entities:
protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) { modelBuilder . Properties () "Description") = p.hasmaxlength (200 )); 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 () "_id") = p.iskey ());} }
Configure Custom convention as shown below:
protected Override void onmodelcreating (Dbmodelbuilder modelBuilder) { modelBuilder.Conventions.Add<PKConvention> ();}
Model Conventions:
Model conventions is based on the underlying model metadata. There is conventions for both CSDL and SSDL. Create A class that implements iconceptualmodelconvention from CSDL conventions and implement istoremodelconvention for SS DL Convention.
Visit CodePlex documentation for more information.
Download Code-first Sample Project for custom Conventions demo.
Entity Framework 6.0 Tutorials (8): Custom Code-first Conventions