Code First support in Entity Framework v6

Code First is next to the DbContext API using an EDMX file, fully supported. Code first is similar to the normal DbContext code generated for Entity Framework v6 but instead of an EDMX file, it will generate a ModelBuilder class, which has the name modelnameModelBuilder.cs/vb and is generated in the Persistence project. The class has one public method and is instantiated in the OnModelCreating method in the DbContext class.

The ModelBuilder class

The ModelBuilder class is located in the Persistence VS.NET project and only has virtual methods, one for each entity type and each value type in the model. These virtual methods allowe you customizability of the mapping code through inheritance. Additionally, the class is a partial class so you can add your own mappings to the class using a partial class.

Generating Code First code

To generate Code First code, the SD.EntityFramework.v6 (Code First) preset should be chosen when generating code. This will then produce similar code to the DbContext API preset but instead of an EDMX file it will produce the ModelBuilder class. Additionally it will produce a different app.config file with a different connection string as the EDMX connection string is no longer needed.

The generated code tries to create a code base which is equal to what you would've written yourself by hand and all Code First constructs are supported.

Limitations

The following elements are not supported in Code First due to limitations with Code First at this point and will be ignored. Work is done by the Entity Framework team to add these to the Code First api in the near future and when that happens we'll add support for these as well.

  • Typed views
  • Table Valued Function calls.

Stored procedure calls which don't have a typed view mapped onto their resultset are supported and get a method generated into the DbContext class, similar to the normal DbContext API.

If a typed view is present and it's a valid mapping for the normal DbContext api, a warning EF0003 is issued which warns the user that typed views will be ignored if Code First is chosen due to the limitation in Code First.

If a relationship has no navigators mapped it's ignored in Code-first mappings, and a warning EF0004 is issued, which warns the user up-front a relationship might not be present in the model as there's no mapping made (as code first doesn't allow to map these kind of relationships).

Re-using most of the DbContext/Poco templates

Most templates for CodeFirst are the same for the DbContext API setup, it adds a new template for the modelbuilder class, changes the app.config template and uses a different context wrapper template to define different input parameters, but it re-uses the same context include template as all the other presets. This means that the same include templates as in DbContext are valid in Code First.