{"id":1597,"date":"2012-04-01T14:05:00","date_gmt":"2012-04-01T19:05:00","guid":{"rendered":"http:\/\/www.wiredprairie.us\/blog\/?p=1597"},"modified":"2012-04-01T14:18:25","modified_gmt":"2012-04-01T19:18:25","slug":"paging-data-with-sql-server-compact","status":"publish","type":"post","link":"https:\/\/www.wiredprairie.us\/blog\/index.php\/archives\/1597","title":{"rendered":"Paging Data with SQL Server Compact"},"content":{"rendered":"
<\/p>\n
If you\u2019re using SQL Server Compact Editition<\/a> version 4 or higher, there\u2019s finally a decent and efficient way to do data paging:<\/p>\n The code above uses Dapper-dot-net<\/a> (with Contrib Extensions) to make the syntax of executing the Query succinct. (Recently, I\u2019ve all but abandoned the Entity Framework in favor of Dapper).<\/p>\n The above code should be straightforward.<\/p>\n Given a table named, StreetNames<\/strong> created thusly:<\/p>\n with some sample data inserted into the table:<\/p>\n you\u2019ll likely want to grab the data in pages. To get the data as pages, you\u2019ll need to pick an index or something ordered (in this case, I used the Id column), specify the starting index and the total number to fetch:<\/p>\n So, using the sample database:<\/p>\n The code loops until it can\u2019t load a full GroupSize.<\/p>\nvar <\/span>streets = db.Query<StreetName<\/span>>(@"SELECT * FROM StreetNames\n ORDER BY Id\n OFFSET @offset ROWS\n FETCH NEXT @rows ROWS ONLY"<\/span>,\n new <\/span>{ offset = group * GroupSize, \n rows = GroupSize });<\/pre>\n
db.Execute(@"CREATE TABLE StreetNames ( \n Id int IDENTITY NOT NULL,\n Name nvarchar(24) NOT NULL,\n CONSTRAINT pk_id PRIMARY KEY (Id))"<\/span>);<\/pre>\n
foreach <\/span>(var <\/span>name in <\/span>GetStreetNames())\n{\n db.Execute("INSERT INTO StreetNames (Name) Values (@Name)"<\/span>,\n new <\/span>{ Name = name });\n}<\/pre>\n
OFFSET @offset ROWS\nFETCH NEXT @rows ROWS ONLY\n<\/span><\/pre>\n
using <\/span>(var <\/span>db = new <\/span>SqlCeConnection<\/span>(connectionString))\n{\n db.Open();\n for <\/span>(var <\/span>group = 0; ; group++)\n {\n Console<\/span>.WriteLine(string<\/span>.Format("== GROUP {0} =="<\/span>, group));\n var <\/span>streets = db.Query<StreetName<\/span>>(@"SELECT * FROM StreetNames\n ORDER BY Id\n OFFSET @offset ROWS\n FETCH NEXT @rows ROWS ONLY"<\/span>,\n new <\/span>{ offset = group * GroupSize, \n rows = GroupSize });\n\n foreach <\/span>(var <\/span>street in <\/span>streets)\n {\n Console<\/span>.WriteLine(string<\/span>.Format("{0} ({1})"<\/span>,\n street.Name, street.Id));\n }\n if <\/span>(streets.Count() < GroupSize) { break<\/span>; }\n }\n}<\/pre>\n
const int <\/span>GroupSize = 8;<\/pre>\n