TREAT (Entity SQL)
Treats an object of a particular base type as an object of the specified derived type.
TREAT ( expression as type)
Arguments
expression
Any valid query expression that returns an entity.Note
The type of the specified expression must be a subtype of the specified data type, or the data type must be a subtype of the type of expression.
type
An entity type. The type must be qualified by a namespace.Note
The specified expression must be a subtype of the specified data type, or the data type must be a subtype of the expression.
Return Value
A value of the specified data type.
Remarks
TREAT is used to perform upcasting between related classes. For example, if Employee derives from Person and p is of type Person, TREAT(p AS NamespaceName.Employee)
upcasts a generic Person instance to Employee; that is, it allows you to treat p as Employee.
TREAT is used in inheritance scenarios where you can do a query like the following:
SELECT TREAT(p AS NamespaceName.Employee)
FROM ContainerName.Person AS p
WHERE p IS OF (NamespaceName.Employee)
This query upcasts Person entities to the Employee type. If the value of p is not actually of type Employee, the expression yields the value null.
Note
The specified expressionEmployee
must be a subtype of the specified data type Person, or the data type must be a subtype of the expression. Otherwise, the expression will result in a compile-time error.
The following table shows the behavior of treat over some typical patterns and some less common patterns. All exceptions are thrown from the client side before the provider gets invoked:
Pattern | Behavior |
---|---|
|
Returns DbNull. |
|
Throws an exception. |
|
Throws an exception/ |
|
Returns EntityType or null. |
|
Throws an exception. |
|
Throws an exception. |
Example
The following Entity SQL query uses the TREAT operator to convert an object of the type People to a collection of objects of the type Student. The query is based on the School Entity Data Model. For information about how to generate this model, see Generating the School Entity Data Model (Entity Framework Quickstart).
SELECT VALUE TREAT (people as SchoolDataLib.Student)
FROM SchoolDataEntities.People as people
WHERE people IS OF( SchoolDataLib.Student)
This example produces the following output:
Chow
Haas
Hamilton
Adams
Paschke
Abrus
Hance
See Also
Concepts
Entity SQL Reference
Nullable Structured Types (Entity SQL)