DataContext ExecuteQuery(Of TResult) Method Unable to cast object of type OneTimeEnumerable Error
In a recent ASP.NET web site project as datasource of a datagrid / gridview object, I used a LINQ to SQL Classes object.
I created the Data Class .dbml file and the data context class DataClasses1DataContext easily.
To get data from database and set the data source of the datagrid, I used the ExecuteQuery (Of TResult) method of the DataContext class within the System.Data.Linq namespace.
DataContext class ExecuteQuery (Of TResult) method directly executes a SQL query on the database and returns the result as objects.
Although the ExecuteQuery method takes two parameters (arguments) which are the query as string and the parameters as Object() array, I do not need any parameters within the query string.
So I did not pass the parameters arguments to the ExecuteQuery (Of T) method while I was calling that DataContext class. Although it is optional it was not stated within the MSDN documentation.
By the way I used the AdventureWorks sample database for the related example asp.net code.
And build the data context using the dbo.Product table within the sample SQL Server database AdventureWorks.
Here is the sample ASP.NET code for binding data to a gridview asp.net data control object using DataContext.ExecuteQuery method :
In the above ASP.NET code, the most important section for fetching data from database is shown below where we define the datasource object and call the datacontext method ExecuteQuery.
Actually you can define the return object container without defining its data type, the ExecuteQuery method will handle it proparly. But if you set the object type as IEnumerable(Of Product), you will be able to use the Product Data Context properties like IEnumerableList.ToList(0).ProductID
Unable to cast object of type OneTimeEnumerable
If you fail to define the return type of the data context class ExecuteQuery method, you may get error similar to "Unable to cast object of type OneTimeEnumerable"
For example, if you set the IEnumerableList object as in type List(Of Product) instead of the correct data type form IEnumerable(Of Product), you will get the following error message :