ObjectDataSource.EnableCaching ObjectDataSource.EnableCaching ObjectDataSource.EnableCaching ObjectDataSource.EnableCaching Property

定义

获取或设置一个值,该值指示 ObjectDataSource 控件是否启用数据缓存。Gets or sets a value indicating whether the ObjectDataSource control has data caching enabled.

public:
 virtual property bool EnableCaching { bool get(); void set(bool value); };
public virtual bool EnableCaching { get; set; }
member this.EnableCaching : bool with get, set
Public Overridable Property EnableCaching As Boolean

属性值

如果为数据源控件启用数据缓存,则为 true;否则为 falsetrue if data caching is enabled for the data source control; otherwise, false. 默认值为 falseThe default is false.

异常

当由 EnableCaching 属性指定的方法返回 SelectMethod 时,会将 DbDataReader 属性设置为 trueThe EnableCaching property is set to true when the method specified by the SelectMethod property returns a DbDataReader.

示例

以下三个示例显示了一个网页、一个代码隐藏页类和一个数据访问类, 该数据访问类从 Northwind 数据库的 Employees 表中检索记录。The following three examples show a Web page, a code-behind page class, and a data-access class that retrieve records from the Employees table in the Northwind database.

第一个示例显示一个网页, 其中包含两ObjectDataSource个控件DropDownList : 控件和一个DetailsView控件。The first example shows a Web page that contains two ObjectDataSource controls, a DropDownList control, and a DetailsView control. 第一个ObjectDataSource控件DropDownList和控件用于检索和显示数据库中的雇员姓名。The first ObjectDataSource control and the DropDownList control are used to retrieve and display employee names from the database. 第二ObjectDataSource个控件DetailsView和控件用于检索和显示用户选择的员工记录。The second ObjectDataSource control and the DetailsView control are used to retrieve and display the employee record that is selected by the user.

ObjectDataSource控件启用了缓存。Caching is enabled for the ObjectDataSource control. 因此, 只会从数据库中检索一次每条记录。Therefore, each record is retrieved only one time from the database. CacheKeyDependency属性设置为 "EmployeeDetails", 但任何字符串值都可以作为键使用。The CacheKeyDependency property is set to "EmployeeDetails", but any string value can work as the key. 网页还包含一个Button控件, 用户可单击该控件来使缓存的数据过期。The Web page also includes a Button control that the user can click to expire the cached data.

<form id="form1" runat="server">
<div>
<asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />
      
    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>
    
 <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      TypeName="Samples.AspNet.CS.EmployeeLogic" 
      EnableCaching="true"
      CacheKeyDependency="EmployeeDetails" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
    
    <asp:Button 
    ID="Button1" 
    runat="server" 
    Text="Check for latest data" 
    OnClick="Button1_Click" />
    
</div>
</form>
<form id="form1" runat="server">
<div>
<asp:objectdatasource
      ID="ObjectDataSource1"
      runat="server"
      SelectMethod="GetFullNamesAndIDs"
      TypeName="Samples.AspNet.CS.EmployeeLogic" />
      
    <p>
    <asp:dropdownlist
      ID="DropDownList1"
      runat="server" 
      DataSourceID="ObjectDataSource1"
      DataTextField="FullName"
      DataValueField="EmployeeID" 
      AutoPostBack="True" 
      AppendDataBoundItems="true">
        <asp:ListItem Text="Select One" Value=""></asp:ListItem>
    </asp:dropdownlist>
    </p>
    
 <asp:objectdatasource
      ID="ObjectDataSource2"
      runat="server"
      SelectMethod="GetEmployee"
      TypeName="Samples.AspNet.CS.EmployeeLogic" 
      EnableCaching="true"
      CacheKeyDependency="EmployeeDetails" >
      <SelectParameters>
        <asp:ControlParameter ControlID="DropDownList1" DefaultValue="-1" Name="empID" />
      </SelectParameters>
    </asp:objectdatasource>
    
    <asp:DetailsView
        ID="DetailsView1"
        runat="server"
        DataSourceID="ObjectDataSource2" 
        AutoGenerateRows="false">  
        <Fields>
            <asp:BoundField HeaderText="Address" DataField="Address" />
            <asp:BoundField HeaderText="City" DataField="City" />
            <asp:BoundField HeaderText="Postal Code" DataField="PostalCode" />
        </Fields>  
    </asp:DetailsView>
    
    <asp:Button 
    ID="Button1" 
    runat="server" 
    Text="Check for latest data" 
    OnClick="Button1_Click" />
    
</div>
</form>

第二个示例演示Load事件的处理程序和Button控件Click事件的处理程序。The second example shows a handler for the Load event and a handler for the Click event of the Button control. 事件处理程序创建一个缓存项, 其中的键设置CacheKeyDependency为值。 LoadThe Load event handler creates a cache item with a key set to the CacheKeyDependency value. 事件处理程序将移除其键与CacheKeyDependency值相等的缓存项。 ClickThe Click event handler removes the cache item whose key is equal to the CacheKeyDependency value. 删除缓存项后, 所有依赖于该键的缓存数据都将过期。When the cache item is removed, all the cached data that is dependent on the key is expired.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        Cache[ObjectDataSource2.CacheKeyDependency] = "CacheExample";
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
    Cache.Remove(ObjectDataSource2.CacheKeyDependency);
    Cache[ObjectDataSource2.CacheKeyDependency] = "CacheExample";
    DetailsView1.DataBind();
}
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
    If Not (IsPostBack) Then
        Cache(ObjectDataSource2.CacheKeyDependency) = "CacheExample"
    End If
End Sub
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
    Cache.Remove(ObjectDataSource2.CacheKeyDependency)
    Cache(ObjectDataSource2.CacheKeyDependency) = "CacheExample"
    DetailsView1.DataBind()
End Sub

第三个示例显示与 Northwind 数据库交互的数据访问类。The third example shows the data access class that interacts with the Northwind database. 类使用 LINQ 查询 Employees 表。The class uses LINQ to query the Employees table. 该示例需要一个表示 Northwind 数据库的 LINQ to SQL 类和 "Employees" 表。The example requires a LINQ to SQL class that represents the Northwind database and the Employees table. 有关详细信息,请参阅如何:在 Web 项目中创建 LINQ to SQL 类。For more information, see How to: Create LINQ to SQL Classes in a Web Project.

public class EmployeeLogic
{
    public static Array GetFullNamesAndIDs()
    {
        NorthwindDataContext ndc = new NorthwindDataContext();

        var employeeQuery =
            from e in ndc.Employees
            orderby e.LastName
            select new { FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID };

        return employeeQuery.ToArray();
    }

    public static Employee GetEmployee(int empID)
    {
        if (empID < 0)
        {
            return null;
        }
        else
        {
            NorthwindDataContext ndc = new NorthwindDataContext();
            var employeeQuery =
                from e in ndc.Employees
                where e.EmployeeID == empID
                select e;

            return employeeQuery.Single();
        }
    }
 
    public static void UpdateEmployeeAddress(Employee originalEmployee, string address, string city, string postalcode)
    {
        NorthwindDataContext ndc = new NorthwindDataContext();
        ndc.Employees.Attach(originalEmployee, false);
        originalEmployee.Address = address;
        originalEmployee.City = city;
        originalEmployee.PostalCode = postalcode;
        ndc.SubmitChanges();
    }
}
Public Class EmployeeLogic
    Public Shared Function GetFullNamesAndIDs() As Array
        Dim ndc As New NorthwindDataContext()

        Dim employeeQuery = _
            From e In ndc.Employees _
            Order By e.LastName _
            Select FullName = e.FirstName + " " + e.LastName, EmployeeID = e.EmployeeID

        Return employeeQuery.ToArray()
    End Function

    Public Shared Function GetEmployee(ByVal empID As Integer) As Employee

        If (empID < 0) Then
            Return Nothing
        Else
            Dim ndc As New NorthwindDataContext()
            Dim employeeQuery = _
                From e In ndc.Employees _
                Where e.EmployeeID = empID _
                Select e

            Return employeeQuery.Single()
        End If
    End Function

    Public Shared Sub UpdateEmployeeAddress(ByVal originalEmployee As Employee, ByVal address As String, ByVal city As String, ByVal postalcode As String)

        Dim ndc As New NorthwindDataContext()
        ndc.Employees.Attach(originalEmployee, False)
        originalEmployee.Address = address
        originalEmployee.City = city
        originalEmployee.PostalCode = postalcode
        ndc.SubmitChanges()
    End Sub
End Class

注解

ObjectDataSource控件支持数据缓存。The ObjectDataSource control supports data caching. 在缓存数据时, 对Select方法的调用从缓存中检索数据, 而不是ObjectDataSource创建业务对象的实例并调用其数据方法。While data is cached, calls to the Select method retrieve data from the cache rather than the ObjectDataSource creating an instance of the business object and calling its data method. 缓存过期后, Select方法从业务对象中检索数据, 然后再次缓存数据。When the cache expires, the Select method retrieves data from the business object, and then caches the data again.

当属性设置为true , 并且CacheDuration属性设置为大于0的值时,控件将自动缓存数据,指示缓存在缓存条目之前存储数据的秒数ObjectDataSource EnableCaching被丢弃。The ObjectDataSource control automatically caches data when the EnableCaching property is set to true and the CacheDuration property is set to a value greater than 0, which indicates the number of seconds that the cache stores data before the cache entry is discarded. 值0表示无限长的缓存。A value of 0 indicates an infinitely long cache.

适用于

另请参阅