May 28, 2010

Define entity from "view"

When you have Entity that mapping to more than one table in a database. You probably have options to do the mapping.


The first option is defined import all the tables into the StorageModels, but not ConceptualModels, define you entity without mapping, then manually edit the edmx file and to define the mapping. Because the entity mapping is manual, you need to define the CRUD manually. You can use store proc to do that.

<EntitySetMapping Name="DummyExes">
            <QueryView>
              select value EFTestModel.DummyEx(p.Id, p.c1, p.c2, c.c3)
              from EFTestModelStoreContainer.Dummy as p
              left join EFTestModelStoreContainer.DummyEx as c
              on p.Id = c.DummyId
            </QueryView>
          </EntitySetMapping>

The second option is defined a view in database, import that view and mapping to your entity. Because database view are normally treated readonly, you can define CRUD operation using stored proc, just like QueryView. Or you edit edmx file, cheat the ef runtime to think the view as talbe, then define insteadof trigger to do the update.