ObjectDataSource and CacheKeyDependency possible bug
-
14-07-2021 - |
Question
I have noticed a quite strange behavior with an ObjectDataSource
using CacheKeyDependency
When I set the CacheKeyDependency
in the declarative .aspx syntax, the ObjectDataSource.Selecting
event (and Selected) gets called twice!!!
(and of course also the related Database SelectMethod
gets called twice)
But, if I remove the CacheKeyDependency
the ObjectDataSource
Selecting Event occurs, correctly, only once!
Speed concerning apart, this could potentially break my code-behind logic if I assume that Selecting/Selected gets called only once...
Have any of you noticed that?
This behavior could be ascribed to a bug in ASP.NET or maybe there some bug in my code?
PS: The timeline of the events are like so, with in bold the duplicated ones:
PageLoad
ODS_Selecting
DataLayer Select
ODS_Selected
ODS_Filtering
GridView_DataBound
**ODS_Selecting**
**DataLayer Select**
**ODS_Selected**
ODS_Filtering
GridView_DataBound
GridView_PreRender
Solution
The Cache
value for the CacheKeyDependency
must be set. If not, the ObjectDataSource
cache is essentially disabled, which can result in the select method being called twice.
See the example in the Microsoft documentation.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Cache[ObjectDataSource2.CacheKeyDependency] = "CacheExample";
}
}
Found the following approach to work the best. The MS example expires the cache when the page load is not a post back.
if (null == Cache[ObjectDataSource2.CacheKeyDependency])
{
Cache[ObjectDataSource2.CacheKeyDependency] = new Object();
}