views:

172

answers:

1

Hi, I was wondering how I can pull down a portion of a table using LINQ To SQL into C# memory space. Let's say I have a database with thousands of records and a GUI interface that shows one record at a time.

When the user clicks the next / previous record button on the GUI the LINQ To SQL datacontext has to go and get the next record - this takes time.

What I would like to do is get a small block of records, say the last n records and store them in memory so the next and previous buttons react much faster.

What I have tried is create a new field of type Table <vw_RawData> called Table_RawData where vw_RawData is a table in my database and was created by Visual Studio when building the datacontext. Then I tried to fill it (onLoad) using

this._Table_Rawdata = (Table<vw_RawData>) 
from c 
in this._Db.vw_RawDatas 
where c.Date > DateTime.Now.AddMonths(-1) 
select c;

This is compiling OK, but at runtime I get the following error... help??

System.InvalidCastException: Unable to cast object of type 'System.Data.Linq.DataQuery1[vw_RawData]' to type 'System.Data.Linq.Table1[vw_RawData]'.

+2  A: 

You can easily get block of records using Take and Skip methods:

yourTable.OrderBy(x => x.Date).Skip(5).Take(3)

This will return 3 records starting from record number 6.

Dmytrii Nagirniak
how can i use that based on dates. if i want 15 days before X and also 15 days after X?
Grant
Absolutely the right way to solve this problem, IMO. The client knows the index and the number of records to retrieve. This is the simplest way to find the right data at the right time. No real need to start storing this stuff in a cache or session. Just select the records on demand by the user. If this was a multi-user app, the answer might be different. No indication was given in the question, though.
p.campbell
@Grant: Assuming that `X` is a `DateTime`: `yourTable.Where(dt => dt > = X.AddDays(-15) `
Jason