From EDMX (database first) to Code First

I’m using Oracle as the provider for my database and have an application that was created with a db first approach. The upside of this approach is the ease of use. Just pick the tables you want to use and add them to your project and voila. Unfortunately this doesn’t work always and is a source of a lot of grief. The downside of this approach is that is hard to maintain and it requires all environments you may be connecting to, to be the same (development / production). The edmx file is not meant to be manually edited, so you shouldn’t be commenting out stuff in there for different environments, unless you are looking for trouble.

From Entity Framework 6 on you can generate code first from your database (yeay !), but I’m currently working in EF5 and need a way to convert my edmx to code first and believe it or not, there is a way ! you can use a tool in the visual studio gallery called EF 5.x dbcontext fluent generator.

These are the steps I followed:

  1. Add EF 5.x dbcontext fluent generator to your project by going to “Tools” (in visual studio 2012) => Extensions and updates => search and install
  2. double click the EDMX file and on the surface right click => add code generation item => pick the fluent generator from the templates => and rename the .tt file to the same name as your edmx file (example : if mymodel.edmx then
  3. Click ok and the mappings should be generated underneath your .edmx file
  4. Run your application/web site => it should work fine
  5. now, you can get rid of the .edmx + .tt + .diagram + .designer.cs  => in order to do this, first copy everything in a diferent (backup) folder, then remove the edmx from visual studio (=> this will delete all sub files unfortunately) => then just copy/paste all good files (non .tt, .diagram, .edmx, .designer.cs) in to visual studio on the location where the edmx file used to be.
  6. now, you need to modify your connectionstring, because code first doesn’t use the same formatting with metadata etc., you should get the normal ado connectionstring.

    1. For Example <add name=MyEntities providerName=Oracle.ManagedDataAccess.Client connectionString=data source=dbname;password=yourpassword;user id=yourusername/>