Export (0) Print
Expand All

ObjectDataSource Class

Updated: July 2009

Represents a business object that provides data to data-bound controls in multitier Web application architectures.

Namespace:  System.Web.UI.WebControls
Assembly:  System.Web (in System.Web.dll)

[ToolboxBitmapAttribute(typeof(ObjectDataSource))]
[AspNetHostingPermissionAttribute(SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermissionAttribute(SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
public class ObjectDataSource : DataSourceControl
<asp:ObjectDataSource />

The ObjectDataSource is an ASP.NET data source control that represents a data-aware middle-tier object or a data interface object to data-bound controls. You can use the ObjectDataSource control in conjunction with a data-bound control to display, edit, and sort data on a Web page with little or no code.

There is no visual rendering of the ObjectDataSource control. It is implemented as a control so that you can create it declaratively and to enable it to participate in state management, optionally. As a result, the ObjectDataSource does not support visual features such as the EnableTheming or SkinID property.

A very common application design practice is to separate the presentation layer from business logic and to encapsulate the business logic in business objects. These business objects form a distinct layer between the presentation layer and the data tier, resulting in a three-tier application architecture. The ObjectDataSource control enables developers to use an ASP.NET data source control while retaining their three-tier application architecture.

The ObjectDataSource control uses reflection to create instances of business objects and to call methods on them to retrieve, update, insert, and delete data. The TypeName property identifies the name of the class that the ObjectDataSource works with. The ObjectDataSource control creates and destroys an instance of the class for each method call; it does not hold the object in memory for the lifetime of the Web request. This is a serious consideration if the business object that you use requires many resources or is otherwise expensive to create and destroy. Using an expensive object might not be an optimal design choice, but you can control the life cycle of the object by using the ObjectCreating, ObjectCreated, and ObjectDisposing events.

NoteNote:

The methods that are identified by the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod properties can be instance methods or static (Shared in Visual Basic) methods. If the methods are static (Shared in Visual Basic), an instance of the business object is not created, and the ObjectCreating, ObjectCreated, and ObjectDisposing events are not raised.

To retrieve data from a business object, set the SelectMethod property with the name of the method that retrieves data. If the method does not return an IEnumerable or DataSet object, the object is wrapped by the runtime in an IEnumerable collection. If the method signature has parameters, you can add Parameter objects to the SelectParameters collection, and then bind them to the values that you want to pass to the method that is specified by the SelectMethod property. In order for the ObjectDataSource to use the parameters, the parameters must match the names and types of the parameters in the method signature. For more information, see Using Parameters with the ObjectDataSource Control.

The ObjectDataSource control retrieves data whenever the Select method is called. This method provides programmatic access to the method that is specified by SelectMethod property. The method that is specified by the SelectMethod property is called automatically by controls that are bound to the ObjectDataSource when their DataBind method is called. If you set the DataSourceID property of a data-bound control, the control automatically binds to data from the data source, as needed. Setting the DataSourceID property is the recommended method for binding an ObjectDataSource control to a data-bound control. Alternatively, you can set the DataSource property, but then you must explicitly call the DataBind method of the data-bound control. You can call the Select method programmatically at any time to retrieve data.

For more information about binding data-bound controls to data source controls, see Binding to Data Using a Data Source Control.

Depending on the capabilities of the business object that the ObjectDataSource control works with, you can perform data operations, such as updates, insertions, and deletions. To perform these data operations, set the appropriate method name and any associated parameters for the operation that you want to perform. For example, for an update operation, set the UpdateMethod property to the name of the business object method that performs updates and add any required parameters to the UpdateParameters collection. If the ObjectDataSource control is associated with a data-bound control, the parameters are added by the data-bound control. In this case, you need to ensure that the parameters names of the method match the field names in the data-bound control. The update is performed when the Update method is called, either explicitly by your code or automatically by a data-bound control. The same general pattern is followed for Delete and Insert operations. Business objects are assumed to perform these types of data operations one record at a time, rather than batched.

The ObjectDataSource control can filter data that is retrieved by the SelectMethod property, if the data is returned as a DataSet or DataTable object. The ObjectDataSource control allows you to cache all types of data, but you should not cache objects that retain resources or state that cannot be shared to service multiple requests (for example, an open SqlDataReader object), because the same instance of the object will be used to service multiple requests. You can set the FilterExpression property to a filtering expression by using a format string syntax and bind values in the expression to parameters that are specified in the FilterParameters collection.

Although the ObjectDataSource does not retain the instance of the business object across multiple requests, it can cache the result of the SelectMethod property. While the data is cached, subsequent calls to the Select method return the cached data instead of creating the business object and calling its SelectMethod using reflection. Caching lets you avoid creating the object and calling its data method at the expense of memory on the Web server. The ObjectDataSource automatically caches data when the EnableCaching property is set to true, and the CacheDuration property is set to the number of seconds that the cache stores data before the cache is discarded. You can also specify a CacheExpirationPolicy property and an optional SqlCacheDependency property.

The following table describes the features of the ObjectDataSource control.

Capability

Requirements

Selecting

Set the SelectMethod property to the name of the business object method that selects data, and include any necessary parameters in the SelectParameters collection either programmatically or by using a data-bound control.

Sorting

Set the SortParameterName property to the name of the parameter in the SelectMethod method that carries the sort criteria.

Filtering

Set the FilterExpression property to a filtering expression and optionally add any parameters to the FilterParameters collection to filter the data when the Select method is called. The method specified by the SelectMethod property must return a DataSet or DataTable.

Paging

Data source paging is supported, if the SelectMethod method contains parameters for the maximum number of records to retrieve and the index of the first record to retrieve. The names of those parameters must be set in the MaximumRowsParameterName and StartRowIndexParameterName properties, respectively. A data-bound control might be able to perform paging itself, even if the ObjectDataSource control does not support paging directly in the method specified by the SelectMethod property. The requirement for the data-bound control to be able to do this is that the method specified by the SelectMethod property return an object that implements the ICollection interface.

Updating

Set the UpdateMethod property to the name of the business object method that updates data, and include any necessary parameters in the UpdateParameters collection.

Deleting

Set the DeleteMethod property to the name of the business object method or function that deletes data, and include any necessary parameters in the DeleteParameters collection.

Inserting

Set the InsertMethod property to the name of the business object method or function that inserts data, and include any necessary parameters in the InsertParameters collection.

Caching

Set the EnableCaching property to true, and the CacheDuration and CacheExpirationPolicy properties according to the caching behavior you want for your cached data.

NoteNote:

When you use the ObjectDataSource class to update or insert data, strings that are entered at the client are not automatically converted from the client culture format to the server culture format. For example, the client culture might specify DD/MM/YYYY as the date format, and the date format on the server might be MM/DD/YYYY. In that case, October 5, 2009 would be entered in a TextBox control as 5/10/2009 but would be interpreted as May 10, 2009. October 15, 2009 would be entered as 15/10/2009, and would be rejected as an invalid date.

As with all data source controls, the ObjectDataSource control is associated with a data source view class. While the ObjectDataSource control is the interface that the page developer uses to work with data, the ObjectDataSourceView class is the interface that data-bound controls work with. Additionally, the ObjectDataSourceView class describes the capabilities of the data source control, and performs the actual work. The ObjectDataSource control has only one associated ObjectDataSourceView, and it is always named DefaultView. While the ObjectDataSourceView object is exposed by the GetView method, many of its properties and methods are wrapped and exposed directly by the ObjectDataSource control. Behind the scenes, the ObjectDataSourceView object performs all data operations, including retrieving, inserting, updating, deleting, filtering, and sorting the data. For more information, see ObjectDataSourceView.

You can use the ObjectDataSource control with a LINQ to SQL class. To do so, you set the TypeName property to the name of the data-context class. You also set the SelectMethod, UpdateMethod, InsertMethod, and DeleteMethod methods to the methods in the data-context class that perform the corresponding operations. You must create an event handler for the ObjectDisposing event in order to cancel disposing of the data-context class. This step is necessary because LINQ to SQL supports deferred execution, whereas the ObjectDataSource control tries to dispose the data context after the Select operation. For more information about how to create LINQ to SQL classes, see How to: Create LINQ to SQL Classes in a Web Project. For an example of how to cancel the disposing of a data context class, see the ObjectDisposing event.

There is no visual rendering of the ObjectDataSource control. It is implemented as a control so that you can create it declaratively and to enable it to participate in state management, optionally. As a result, the ObjectDataSource does not support visual features such as the EnableTheming or SkinID property.

TopicLocation
How to: Bind to Data in a Templated ControlBuilding ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source ControlsBuilding ASP .NET Web Applications
How to: Bind to Data in a Templated ControlBuilding ASP .NET Web Applications
How to: Secure Connection Strings When Using Data Source ControlsBuilding ASP .NET Web Applications
Walkthrough: Data Binding Web Pages with a Visual Studio Data ComponentBuilding ASP .NET Web Applications in Visual Studio
How To: Secure Connection Strings when Using Data Source Controls (Visual Studio)Building ASP .NET Web Applications in Visual Studio
How to: Add Repeater Web Server Controls to a Web Forms Page (Visual Studio)Building ASP .NET Web Applications in Visual Studio
Walkthrough: Data Binding to a Custom Business ObjectBuilding ASP .NET Web Applications in Visual Studio
How to: Bind to Data in a Templated Control in Visual StudioBuilding ASP .NET Web Applications in Visual Studio

This section contains two code examples. The first code example shows how a GridView control can display data by using an ObjectDataSource object on an ASP.NET Web page. The second code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use.

The following code example demonstrates how a GridView control can display data using an ObjectDataSource control on a Web Forms page. The ObjectDataSource identifies the partially or fully qualified class name of a business object with its TypeName property and a business object method that is called to retrieve data with its SelectMethod property. At run time, the object is created and the method is called using reflection. The GridView control enumerates through the IEnumerable collection that is returned by the SelectMethod property and displays the data.

<%@ Register TagPrefix="aspSample" Namespace="Samples.AspNet.CS" Assembly="Samples.AspNet.CS" %>
<%@ Page language="c#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
  <head>
    <title>ObjectDataSource - C# Example</title>
  </head>
  <body>
    <form id="Form1" method="post" runat="server">

        <asp:gridview
          id="GridView1"
          runat="server"
          datasourceid="ObjectDataSource1" />

        <asp:objectdatasource
          id="ObjectDataSource1"
          runat="server"
          selectmethod="GetAllEmployees"
          typename="Samples.AspNet.CS.EmployeeLogic" />

    </form>
  </body>
</html>

The following code example provides an example middle-tier business object that this and many other ObjectDataSource code examples use. The code example consists of the following two basic classes:

  • The EmployeeLogic class, which is a stateless class that encapsulates business logic.

  • The NorthwindEmployee class, which is a model class containing only the basic functionality that is required to load and persist data from the data tier.

An additional NorthwindDataException class is provided as a convenience.

This set of example classes works with the Northwind Traders database, which is available with Microsoft SQL Server and Microsoft Access. For a complete working example, you must compile and use these classes with the Web Forms code examples that are provided. For information about how to install the Northwind Traders database, see How to: Install Sample Databases.

This example is designed to be simple and easy to follow and to demonstrate one of the most common ways a business object interacts with an ObjectDataSource control. It is not a design recommendation. In some examples, additional methods are added to the EmployeeLogic or NorthwindEmployee classes, or modifications are made to this set of classes to demonstrate fundamental concepts.

namespace Samples.AspNet.CS {

using System;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;
using System.Web.UI.WebControls;
  // 
  // EmployeeLogic is a stateless business object that encapsulates 
  // the operations one can perform on a NorthwindEmployee object. 
  // 
  public class EmployeeLogic {

    // Returns a collection of NorthwindEmployee objects. 
    public static ICollection GetAllEmployees () {
      ArrayList al = new ArrayList();

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

      SqlDataSource sds
        = new SqlDataSource(cts.ConnectionString, "SELECT EmployeeID FROM Employees");

      try {

        IEnumerable IDs = sds.Select(DataSourceSelectArguments.Empty);

        // Iterate through the Enumeration and create a 
        // NorthwindEmployee object for each ID. 
        foreach (DataRowView row in IDs) {
          string id = row["EmployeeID"].ToString();
          NorthwindEmployee nwe = new NorthwindEmployee(id);
          // Add the NorthwindEmployee object to the collection.
          al.Add(nwe);
        }
      }
      finally {
        // If anything strange happens, clean up.
        sds.Dispose();
      }

      return al;
    }
    public static NorthwindEmployee GetEmployee(object anID) {
      return new NorthwindEmployee(anID);
    }

    public static void UpdateEmployeeInfo(NorthwindEmployee ne) {
      bool retval = ne.Save();
      if (! retval) { throw new NorthwindDataException("UpdateEmployee failed."); }
    }

    public static void DeleteEmployee(NorthwindEmployee ne) { }

  }

  public class NorthwindEmployee {

    public NorthwindEmployee () {
      ID = DBNull.Value;
      lastName = "";
      firstName = "";
      title="";
      titleOfCourtesy = "";
      reportsTo = -1;
    }

    public NorthwindEmployee (object anID) {
      this.ID = anID;

      ConnectionStringSettings cts = ConfigurationManager.ConnectionStrings["NorthwindConnection"];

		SqlConnection conn = new SqlConnection (cts.ConnectionString);
      SqlCommand sc =
        new SqlCommand(" SELECT FirstName,LastName,Title,TitleOfCourtesy,ReportsTo " +
                       " FROM Employees " +
                       " WHERE EmployeeID = @empId",
                       conn);
      // Add the employee ID parameter and set its value.
      sc.Parameters.Add(new SqlParameter("@empId",SqlDbType.Int)).Value = Int32.Parse(anID.ToString());
      SqlDataReader sdr = null;

      try {
        conn.Open();
        sdr = sc.ExecuteReader();

        // This is not a while loop. It only loops once. 
        if (sdr != null && sdr.Read()) {
          // The IEnumerable contains DataRowView objects. 
          this.firstName        = sdr["FirstName"].ToString();
          this.lastName         = sdr["LastName"].ToString();
          this.title            = sdr["Title"].ToString();
          this.titleOfCourtesy  = sdr["TitleOfCourtesy"].ToString();
          if (! sdr.IsDBNull(4)) {
            this.reportsTo        = sdr.GetInt32(4);
          }
        }
        else {
          throw new NorthwindDataException("Data not loaded for employee id.");
        }
      }
      finally {
        try {
          if (sdr != null) sdr.Close();
          conn.Close();
        }
        catch (SqlException) {
          // Log an event in the Application Event Log. 
          throw;
        }
      }
    }

    private object ID;

    private string lastName;
    public string LastName {
      get { return lastName; }
      set { lastName = value; }
    }

    private string firstName;
    public string FirstName {
      get { return firstName; }
      set { firstName = value;  }
    }

    private string title;
    public String Title {
      get { return title; }
      set { title = value; }
    }

    private string titleOfCourtesy;
    public string Courtesy {
      get { return titleOfCourtesy; }
      set { titleOfCourtesy = value; }
    }

    private int    reportsTo;
    public int Supervisor {
      get { return reportsTo; }
      set { reportsTo = value; }
    }

    public bool Save () {
      return true;
    }
  }

  internal class NorthwindDataException: Exception {
    public NorthwindDataException(string msg) : base (msg) { }
  }
}

System.Object
  System.Web.UI.Control
    System.Web.UI.DataSourceControl
      System.Web.UI.WebControls.ObjectDataSource

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

.NET Framework

Supported in: 3.5, 3.0, 2.0

Date

History

Reason

July 2009

Added a note explaining how data formats that vary by culture are handled.

Customer feedback.

Community Additions

ADD
Show:
© 2014 Microsoft