Shawn Wildermuth's Rants and Raves

Thanks for visiting my blog! See more about me here: About Me

Polymorphic Entity Framework Designer Example
Polymorphic Entity Framework Designer Example
August 31, 2007


I’ve been digging into the latest version of theEntity Framework Beta (and designer CTP) that dropped a few days ago. I’ve concocted a small example that shows the derivation model in the Entity Framework. Essentially it is a small model that has a Producttype and two types that derive from that: ActiveProduct and DiscontinuedProduct:

Figure 1: Simple Model

The new design tools are pretty basic but interesting nonetheless. They seem to be modeled after the LINQ designer (which doesn’t make me excited).  The designer has a surface to draw types (or they can be created from database metadata) and create relationships between types (as seen in figure 1 above).  In addition, there are two information panes: Entity Model Browser and Entity Mapping Details:

Figure 2

Figure 2: The complete Designer Experience (Click image for full size)

The idea of this simple model is to show how you can specify derived types in the designer. The derivation in our case evolves around the Discontinued field in the Products table in the Northwind database. The way that different types are typed in the model is using Conditions.  In our case we are typing the database data as a Product if the Discontinued field is NULL (which should never happen really, but the designer doesn’t seem to support the notion of an abstract type yet); if the Discontinued field is true (or 1) then its a DiscontinuedProduct type; and if the Discontinued  field is false (or 0) then its an ActiveProduct.  You can see these mapped in the Entity Mapping Details below:

Figure 3

Figure 3: ActiveProduct Mapping

Figure 4

Figure 4: DiscontinuedProduct Mapping

Once we have the model defined, we can use Object Services to query our data based on type (I could have used LINQ but I think the Entity SQL is clearer in this case):

-- Returns all Products
  FROM NWEntities.Products as p

-- Returns only DiscontinuedProducts
  FROM NWEntities.Products as p 
 WHERE p IS OF(NWModel.DiscontinuedProduct)

-- Returns only ActiveProducts
  FROM NWEntities.Products as p 
 WHERE p IS OF(NWModel.ActiveProduct)

Feel free to download the demo (it only works if you have Orcas Beta 2 and the Entity Framework bits installed) and let me know what you think.