Refactor Entity Framework code to use views instead of tables?

Tag: entity-framework-4.1 , entity-framework-4.3 Author: wjx_229837547 Date: 2012-03-13

We are possibly looking at switching our tables, for views in EF 4.3.1.

We are using db first via the edmx file, so it generates our entities and dbcontext.

Has anyone got any tips for remapping our entities from tables to views?

Is this prone to disaster? We've had trouble with updating the edmx file in the past via the designer where the underlying changes weren't reflected deep somewhere within the code and we ended up with missing columns.

Or will views act very similar to tables in the EF world?

Best Answer

Designer handles views in completely different way - first of all all views used by EF through designer are read only unless you map stored procedures or custom SQL commands to insert, update and delete operation for each entity you want to modify.

Normally if you have updatable view you can simply modify SSDL part of EDMX and cheat it to pretend that the view is actually a table but this has two consequences:

  • You must modify EDMX directly as XML
  • You must not use Update from database any more because it always deletes whole SSDL part and creates a new one without your changes = you must maintain your EDMX manually or buy some extension for VS which will allow you updating only selected tables.

comments:

Great answer as always thanks @Ladislav. Interesting stuff on the potential problems with using views, I think I may of come across an extension, but no word if it works with 4.1+ and the QA is broken in the gallery. But hopefully it might help: visualstudiogallery.msdn.microsoft.com/… thanks again.