Поделиться через


EntityDataSource Web Server Control Overview

The EntityDataSource control supports data binding scenarios in Web applications that use the ADO.NET Entity Framework. Like the other Web server data source controls, the EntityDataSource control manages create, read, update, and delete operations against a data source on behalf of data-bound controls on the same page.

Queries are constructed automatically and can be customized by using fragments of Entity SQL syntax assigned to the Where, OrderBy, GroupBy and Select properties. You can supply parameter values to these operations from page controls, cookies, query parameters appended to the page URI, and other ASP.NET parameter objects. You can also customize queries by handling the QueryCreated event or using the QueryExtender control.

The Object Context

You must configure the properties of the EntityDataSource control to be able to connect to the EDM and return the correct entity types. When you set the ConnectionString and DefaultContainerName properties, the EntityDataSource control can create the ObjectContext it uses to execute object queries. When you set the EntitySetName and EntityTypeFilter properties, you define the type of ObjectQuery<T> that the EntityDataSource control composes.

You can initialize the ConnectionString property of the EntityDataSource control from a named EDM connection string stored in the connectionStrings element of the application configuration file. When you create the EDM by using the Entity Data Model Wizard, you create a named EDM connection in the application configuration file. You can then view this connection as an option in the Configure Data Source wizard of the EntityDataSource designer.

The ObjectContext object encapsulates a connection to the database, metadata that describes the model, and an ObjectStateManager object that tracks objects during create, update, and delete operations. The ContextTypeName property of the EntityDataSource control is a string that specifies the fully qualified type name of the typed ObjectContext that the EntityDataSource control uses. If the ContextTypeName property is not specified, you must set both the DefaultContainerName and ConnectionString properties for the EntityDataSource control to create the ObjectContext. Note, that if you specify the DefaultContainerName and ConnectionString properties, the base ObjectContext instance will be created, not an instance of the ObjectContext derived type. The EntityDataSource designer sets the DefaultContainerName and ConnectionString properties. You can access the ObjectContext instance that the EntityDataSource control uses from the ContextCreated event.

Entity Types

In the EDM, an entity set is a logical container for entity types that are defined in the conceptual schema. You can specify the entity set of the type of objects that the EntityDataSource control accesses through the EntitySetName. The value of the EntitySetName property is the default SELECT statement that the control uses. The setting is not required if the query is specified as an Entity SQL expression supplied to the CommandText property.

When the EntityDataSource control must return a specific derived type, you must also specify the name of this derived type in the EntityTypeFilter property. If the EntitySetName property specifies an entity set that can generate polymorphic results, the EntityTypeFilter property is required to be able to edit data. Setting the EntityTypeFilter property has the same effect as applying the OfType<TResultType> method to the ObjectQuery<T>. If the data binding is read-only then the EntityTypeFilter property is not required. In this case, the properties of the object that the query returns will be those of the default entity type for the entity set.

You can define which objects return along with the specifically queried object by using the Include property of the EntityDataSource control to specify a comma-separated list of query paths. Each comma-separated value in the string is passed, without modification, as a separate call to the Include method of the ObjectQuery<T> that is the data source for the EntityDataSource control.

The string supplied to the Include property uses the same format as the string passed to the Include method of ObjectQuery<T>.

Filtering Data

The Where property of the EntityDataSource control is a string that represents a WHERE clause that is the predicate of an Entity SQL query. This string is passed, without modification, to an ObjectQuery<T> that is executed by Object Services. This query is the source of the data regulated by the EntityDataSource control. The string supplied to the Where property uses the same format as the string passed to the Where method of ObjectQuery<T>.

If you want to compare an entity type property and expression for equality, you can use the AutoGenerateWhereClause property. When the AutoGenerateWhereClause property of the EntityDataSource control is set to true, the control automatically generates a WHERE clause from the parameters in the ParameterCollection of the WhereParameters property. The Name property of each parameter has to match an entity type property name that is included in the query results. If you set the AutoGenerateWhereClause property to true, you should not explicitly assign a WHERE clause to the Where property.

Like the Where method of the ObjectQuery<T> class, parameters can be passed to the predicate assigned to the Where property. The WhereParameters property of the EntityDataSource control specifies a ParameterCollection that contains the parameters to supply to the WHERE clause of the query. The WhereParameters property uses named arguments to refer to the parameters specified in the string supplied to the Where property.

If the WhereParameters property is not set, no parameter substitution is made. All of the parameter names in the WHERE clause, prefixed by the "@" symbol, must have a matching name in the ParameterCollection. Null values are not allowed for parameters in a ParameterCollection.

Ordering Data

You can order the results in your EntityDataSource control by using the OrderBy property. The OrderBy property of the EntityDataSource control is a string that represents an ORDER BY expression of an Entity SQL query. This string is passed, without modification, to the ObjectQuery<T> that serves as the data source of the EntityDataSource control. The string supplied to the OrderBy property uses the same format as the string passed to the OrderBy method of ObjectQuery<T>.

You can automatically generate the ORDER BY clause by setting the AutoGenerateOrderByClause property of the EntityDataSource control to true. The EntityDataSource control will then automatically generate an ORDER BY clause from the parameter in the ParameterCollection that is assigned to the OrderByParameters property. This eliminates the need to explicitly assign an ORDER BY clause to the OrderBy property. When you automatically generate the ORDER BY clause from the OrderByParameters property, you must verify that the Name property of the parameter in the collection identifies a single property of the item returned from the query.

Like the OrderBy method of the ObjectQuery<T> class, you can pass parameters to the ORDER BY clause in the OrderBy property. You must define the OrderByParameters property of the EntityDataSource control to specify a ParameterCollection for the ORDER BY clause of the query. The OrderByParameters property uses a named argument to refer to the parameter assigned in the OrderBy property.

If you do not define the OrderByParameters property, no parameter substitution is made. The parameter name in the ORDER BY clause, prefixed by the "@" symbol, must have a matching name in the ParameterCollection. Null values are not allowed for parameters in a ParameterCollection.

The CommandText Property

The CommandText property of the EntityDataSource control enables you to specify a query that uses a custom Entity SQL expression. Like the SELECT statement, the Entity SQL expression in the CommandText property creates a projection of the original data that is not updatable.

When you assign CommandText to the EntityDataSource control, you can no longer update, insert, or delete through the control. In this case, the methods CanDelete, CanInsert, and CanUpdate of the related EntityDataSourceView control all return false.

Managing the Object Context

When using the EntityDataSource control, you can provide your own ObjectContext instance in the ContextCreating event. The control uses this ObjectContext instance instead of creating a new one. You can also prevent the EntityDataSource control from disposing the ObjectContext in the EntityDataSourceContextDisposingEventArgs event. This is useful when you want to maintain a single ObjectContext instance in your page to be used by more than one control.

The EntityDataSourceContextCreatingEventArgs object has a Context property that can be assigned to an existing ObjectContext in the ContextCreating event handler.

The following pattern describes how to use an ObjectContext with more than one instance of the EntityDataSource control:

  1. Instantiate the ObjectContext in the page's Load event, and assign it to a class member variable.

  2. Handle the EntityDataSourceContextCreatingEventArgs event, and assign the ObjectContext member to the Context property of the EntityDataSourceContextCreatingEventArgs object.

  3. Handle the ContextDisposing event, and set the Cancel property of the EntityDataSourceContextDisposingEventArgs object to true. This prevents the disposal of the ObjectContext.

  4. Repeat steps 2 and 3 for each EntityDataSource control in the page.

  5. Call the Dispose method to dispose the ObjectContext. The context is also disposed when the page is unloaded.

The following code shows how to create an ObjectContext variable for the Page object and assign it to the Context property of the EntityDataSourceContextCreatingEventArgs object.

public partial class _Default : System.Web.UI.Page
    {
        AdventureWorksModel.AdventureWorksEntities objCtx =
            new AdventureWorksModel.AdventureWorksEntities();

        protected void EntityDataSource2_ContextCreating(object sender, 
            EntityDataSourceContextCreatingEventArgs e)
        {
            e.Context = objCtx;
        }
    }

To keep this objCtx member for future reference, cancel the ContextCreated event as shown by the following code.

        protected void EntityDataSource2_ContextDisposing(object sender, 
            EntityDataSourceContextDisposingEventArgs e)
        {
            e.Cancel = true;
        }

Security Considerations

The following list describes security considerations specific to the EntityDataSource control.

  • Privilege level
    The component opens a connection using the connection string supplied. The privilege level of the connection depends on the connection and server configuration.

  • Access control
    Pages that can produce queries of significant cost should be safeguarded under access control.

  • Unverified input
    Unverified input of query fragments or complete queries should not be exposed to the client side. Applications should always use parameters as an input for queries.

  • Thread safety
    The component is not thread safe because ASP.NET does not require it.

  • Exception messages
    The Entity Framework exposes fragments of metadata information in exception messages. The EntityDataSource control does not try to safeguard metadata from being exposed this way.

  • Validation of post-back calls
    By default, ASP.NET validates the possible arguments for post-back calls on the server. Turning off this feature may severely compromise security of any Web application.

  • Stack trace
    By default, ASP.NET does not show the stack trace of exceptions in the error page. Turning on this feature may lead to disclosure of some metadata details, as some exception messages may contain fragments of metadata.

See Also

Other Resources

Getting Started with the Entity Framework