Skip to content
martinjw edited this page Nov 30, 2016 · 1 revision

Reverse Engineer Entity Framework Code First

If you have an existing database, you can still use EF Code First for data access.

Note that EF Code First is primarily designed for Sql Server (full, Express and LocalDb versions) and Sql Server Ce 4. You'll need a third party driver to support other languages (such as Devart, which supports Oracle, MySql, SQLite and PostgreSql).

UI

  • Run DatabaseSchemaViewer,exe, enter the connection string and click the "Read Schema" button.
  • Then click the "Code gen" button on the toolbar.
  • Enter the file path, type is C#. Enter the namespace, and the Project Type is "PocoEntityCodeFirst".
  • Click the "Generate" button.

Your project is ready in the file path you selected.

Recommended settings

There are a couple of "hidden" settings that are useful in Code First. You can turn them on by opening the "DatabaseSchemaViewer.exe.config" file in Notepad and changing these settings to True:

      <setting name="CodeGenUseForeignKeyIdProperties" serializeAs="String">
        <value>False</value>
      </setting>
      <setting name="CodeGenUsePluralizingNamer" serializeAs="String">
        <value>False</value>
      </setting>
  • CodeGenUseForeignKeyIdProperties creates two properties for each foreign key - an entity property and an Id property. This "de-normalized" entity allows you to change relationships without loading entities.
  • CodeGenUsePluralizingNamer names the DbSets and foreign key many-relationships with plurals (the default is "xCollection"). So a DbSet of Category entities would be named "Categories" instead of "CategoryCollection".
  • CodeGenWriteIndexAttribute adds EF 6.1 Index attributes to indexed properties (except the primary key and foreign keys). In code use codeWriterSettings.WriteCodeFirstIndexAttribute

Code

You can use the API like this:

var settings = new CodeWriterSettings 
{ 
  Namespace = "Northwind", 
  CodeTarget= CodeTarget.PocoEntityCodeFirst,
  Namer = new PluralizingNamer()
};
var codeWriter = new CodeWriter(schema, settings);
codeWriter.Execute(directory);

Oracle/ Devart

The generated DbContext contains special configuration for Devart: see http://www.devart.com/dotconnect/oracle/docs/?EFProviderConfiguration.html for more configuration. Spatial

(v1.2.7.0+) If "geometry" or "geography" types are detected, DbGeometry and DbGeography properties are created. NOTE spatials in EF 5 are only available in .net 4.5, so ensure the project is targeting the right framework, and you are using Entity Framework 5 (and not v4.4.0.0 for .net 4). In EF 6 you can use .net 4.0 projects.

Spatial types also work against Oracle sdogeometry and sdogeography types using Devart (see http://blogs.devart.com/dotconnect/using-entity-framework-spatials-with-oracle-spatial-and-sharpmap.html).

Entity Framework Power Tools

Microsoft have a free tool called Entity Framework 6.1.0 Tools for Visual Studio 2012 & 2013 (previously Entity Framework Power Tools ). When installed (as a Visual Studio extension) you can right click a project, select "Entity Framework" and select "Reverse Engineer Code First".

It reads the database and creates an entity class for each table (with a property for each column). It also creates a DbContext and the mapping files. See EF Team Design Notes.

The DatabaseSchemaReader will also reverse engineer a database into code first. Both this code and the Power Tools have similar limitations (they can't infer inheritance, table or entity splitting, enums). The goal of both tools is the same: generate a starting point that can then be customized, not supporting repeated regeneration from databases.

The differences are as follows:

  • EF Power Tools is a Visual Studio extension, DatabaseSchemaReader is a standalone GUI or a library API. If you use the API, you have full programmatic control to name classes and properties, and exclude or add tables, views and columns.
  • The default naming rules are more friendly. A table named STOCK_TYPE is named by the EF Power Tools as STOCK_TYPE; the DatabaseSchemaReader names it as StockType. If you use the API you can rename everything.
  • Both tools use the standard validation data annotations. This enables them to be used in GUIs like ASP.Net MVC. EF Power Tools also uses the TableAttribute (for table name), but DatabaseSchemaReader uses fluent mapping. Optionally, DatabaseSchemaReader will write Index attributes.
  • EF Power Tools maps relationships in the DbContext using fluent mapping, but knows the underlying EF conventions and therefore the mapping is minimal. DatabaseSchemaReader uses class mapping files and is more explicit, even if it is repeating conventions.
  • DatabaseSchemaReader adds ToString, GetHashCode and Equals overloads to each entity class.
  • EF Power Tools creates a DbContext with DbSets and getter/setter. DatabaseSchemaReader creates a DbContext with IDbSets with getter only.
  • Relationships are created in both tools. For each many to one relationship EF Power Tools creates two properties- the entity property and an entity id property. By default, DatabaseSchemaReader only creates the entity property, but it has an option (see below) to create the foreign key id property. In real-world code first applications, these two properties can be useful.
  • EF Power Tools allows you to customize the templates that it uses. DatabaseSchemaReader doesn't (although the source code is available).