After a LINQ to Entities query is converted to command trees and executed, the query results are usually returned as one of the following:
A collection of zero or more typed entity objects or a projection of complex types in the conceptual model.
CLR types supported by the conceptual model.
When the query has executed against the data source, the results are materialized into CLR types and returned to the client. All object materialization is performed by the Entity Framework. Any errors that result from an inability to map between the Entity Framework and the CLR will cause exceptions to be thrown during object materialization.
If the query execution returns primitive conceptual model types, the results consist of CLR types that are stand-alone and disconnected from the Entity Framework. However, if the query returns a collection of typed entity objects, represented by ObjectQuery<T>, those types are tracked by the object context. All object behavior (such as child/parent collections, change tracking, polymorphism, and so on) are as defined in the Entity Framework. This functionality can be used in its capacity, as defined in the Entity Framework. For more information, see Working with Objects.
Struct types returned from queries (such as anonymous types and nullable complex types) can be of
null value. An EntityCollection<TEntity> property of a returned entity can also be of
null value. This can result from projecting the collection property of an entity that is of
null value, such as calling FirstOrDefault on an ObjectQuery<T> that has no elements.
In certain situations, a query might appear to generate a materialized result during its execution, but the query will be executed on the server and the entity object will never be materialized in the CLR. This can cause problems if you are depending on side effects of object materialization.
The following example contains a custom class,
MyContact, with a
LastName property. When the
LastName property is set, a
count variable is incremented. If you execute the two following queries, the first query will increment
count while the second query will not. This is because in the second query the
LastName property is projected from the results and the
MyContact class is never created, because it is not required to execute the query on the store.
[!CODE [DP L2E Materialization Example#MaterializationSideEffects](../CodeSnippet/VS_Snippets_Data/DP L2E Materialization Example#materializationsideeffects)]
[!CODE [DP L2E Materialization Example#MyContactClass](../CodeSnippet/VS_Snippets_Data/DP L2E Materialization Example#mycontactclass)]