Flattening Objects (EntityDataSource)
In some cases, the EntityDataSource control creates wrappers around entities. This topic describes scenarios when the wrapper is created and shows how to get the entity object from the wrapper.
When you initialize the EntityDataSource control by using the EntitySetName property, the EntityDataSource wraps each entity instance in the results in an object of the ICustomTypeDescriptor type. The wrapper object exposes PropertyDescriptors that enable bi-directional data binding for objects of complex type and for objects that participate in a relationship. The PropertyDescriptor also provides access to foreign key information. As a result, when you try to get your original entity object, for instance from the arguments of the RowDataBound event of the GridView control, you will get a wrapper object instead of the entity object.
Note
The entity objects will not be wrapped if you use CommandText to specify a query that returns entity objects or projection of specific properties, or if you use Select to produce projection queries.
The following code shows how to get an entity object from a wrapper object:
protected void ProductsGridView_RowDataBound(object sender, GridViewRowEventArgs e)
{
var entity = dataItem as Product;
if (entity == null)
{
var td = dataItem as ICustomTypeDescriptor;
if (td != null)
{
entity = (Product)td.GetPropertyOwner(null);
}
}
}
If you are using the .NET Framework version 4 or later, you can include foreign key properties in your model. This eliminates the need for wrapper objects in many cases. To turn off wrapper creation, set the EnableFlattening property to false. By default EnableFlattening is true. If your conceptual model includes foreign key properties and does not contain complex types, the EntityDataSource designer will set EnableFlattening to false at design-time to avoid creating entity wrapper objects.