Export (0) Print
Expand All

TREAT (Entity SQL)

Treats an object of a particular base type as an object of the specified derived type.


TREAT ( expression as type)

expression

Any valid query expression that returns an entity.

NoteNote

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.

NoteNote

The specified expression must be a subtype of the specified data type, or the data type must be a subtype of the expression.

A value of the specified data type.

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.

NoteNote

The specified expression Employee 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

TREAT (null AS EntityType)

Returns DbNull.

TREAT (null AS ComplexType)

Throws an exception.

TREAT (null AS RowType)

Throws an exception/

TREAT (EntityType AS EntityType)

Returns EntityType or null.

TREAT (ComplexType AS ComplexType)

Throws an exception.

TREAT (RowType AS RowType)

Throws an exception.

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

Community Additions

Show:
© 2014 Microsoft