Entity Framework: Creating a model using views instead of tables

In Entity Framework, Views are “readonly” due to the DefiningQuery element. There are two approaches to make a view editable:

  1. Create stored procedures for Insert/Update/Delete: This is described in this document and this walkthrough.
  2. Make Entity Framework treat views as tables by doing some manual modifications in the generated EDMX file: This is described in this post.

A few days back, I created an entity model on top of views instead of tables. Since my physical model consisted of Views and not tables, so Entity Designer was not able to infer primary keys/relations etc., and I had to create them manually. In this post, I will highlight the steps I took to create a working entity model by hand. Please read at your own risk and feel free to contribute your ideas using the comments section. Note that not all views are updatable, and this MSDN document describes certain properties that a view definition must hold in order to be updatable.

Assume we have a JobWBS and a ResourceAssignment view with a One-to-Many relationship as depicted below:


If we try to create an “ADO.NET Entity Data Model” for the above views, Visual Studio will generate a model similar to this one.


Notice that the designer marked all fields as primary keys. We need to manually edit the generated edmx file by opening it with “XML editor”.


You will also notice the following warnings inside the edmx xml:

Errors Found During Generation:
warning 6002: The table/view 'testdb.dbo.vw_JobWBS' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.

Read the rest of this entry »

RIA Services: Working with Foreign Keys/Associations in Entity Framework

Yesterday, I got an strange observation regarding RIA Services. I needed to created an Entity Model from views instead of tables so it had no foreign key associations defined. I manually created the associations and was finally able to get a working model. I then added a RIA Domain Service and got the following error upon build:

“Unable to retrieve AssociationType for association ‘JobWBS_ResourceAssignment'”

Strange. But after some effort I came to know that the current(July 2009) preview of RIA services expects all the associations in the default foreign key naming convention, i.e., FK_ForeignKeyTable_PrimaryKeyTable. In my case, I had a 1-Many relationship between JobWBS and ResourceAssignment so I changed the association name to FK_ResourceAssignment_JobWBS and the project built successfully.

Update: If you are still not able to get rid of the error. Its probably because your SSDL schema does not have the proper associations defined. Have a look at this post on how to manually define associations in the physical (storage) model.