<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	
	xmlns:georss="http://www.georss.org/georss"
	xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#"
	>

<channel>
	<title>Dapper &#8211; WiredPrairie</title>
	<atom:link href="blog/archives/tag/dapper/feed" rel="self" type="application/rss+xml" />
	<link>/blog</link>
	<description>Yet another tech blog.</description>
	<lastBuildDate>Sun, 01 Apr 2012 19:18:25 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.0</generator>
<site xmlns="com-wordpress:feed-additions:1">193486638</site>	<item>
		<title>Paging Data with SQL Server Compact</title>
		<link>/blog/index.php/archives/1597</link>
		
		<dc:creator><![CDATA[Aaron]]></dc:creator>
		<pubDate>Sun, 01 Apr 2012 19:05:00 +0000</pubDate>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Dapper]]></category>
		<category><![CDATA[Sql Server Compact Edition]]></category>
		<category><![CDATA[SSCE]]></category>
		<guid isPermaLink="false">/blog/?p=1597</guid>

					<description><![CDATA[If you’re using SQL Server Compact Editition version 4 or higher, there’s finally a decent and efficient way to do data paging: var streets = db.Query&#60;StreetName&#62;(@&#34;SELECT * FROM StreetNames ORDER BY Id OFFSET @offset ROWS FETCH NEXT @rows ROWS ONLY&#34;, new { offset = group * GroupSize, rows = GroupSize }); The code above uses [&#8230;]]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" style="background-image: none; border-bottom: 0px; border-left: 0px; margin: 0px auto; padding-left: 0px; padding-right: 0px; display: block; float: none; border-top: 0px; border-right: 0px; padding-top: 0px" title="image" border="0" alt="image" src="blog/wpcontent/uploads/2012/04/image9.png" width="402" height="338" /></p>
<p>If you’re using <a href="http://www.microsoft.com/sqlserver/en/us/editions/compact.aspx">SQL Server Compact Editition</a> version 4 or higher, there’s finally a decent and efficient way to do data paging:</p>
<pre class="code"><span style="color: blue">var </span>streets = db.Query&lt;<span style="color: #2b91af">StreetName</span>&gt;(<span style="color: #a31515">@&quot;SELECT * FROM StreetNames
                   ORDER BY Id
                   OFFSET @offset ROWS
                   FETCH NEXT @rows ROWS ONLY&quot;</span>,
                        <span style="color: blue">new </span>{ offset = group * GroupSize, 
                            rows = GroupSize });</pre>
<p>The code above uses <a href="http://code.google.com/p/dapper-dot-net/">Dapper-dot-net</a> (with Contrib Extensions) to make the syntax of executing the Query succinct. (Recently, I’ve all but abandoned the Entity Framework in favor of Dapper).</p>
<p>The above code should be straightforward.</p>
<p>Given a table named, <strong>StreetNames</strong> created thusly:</p>
<pre class="code">db.Execute(<span style="color: #a31515">@&quot;CREATE TABLE StreetNames (          
            Id int IDENTITY NOT NULL,
            Name nvarchar(24) NOT NULL,
            CONSTRAINT pk_id PRIMARY KEY (Id))&quot;</span>);</pre>
<p>with some sample data inserted into the table:</p>
<pre class="code"><span style="color: blue">foreach </span>(<span style="color: blue">var </span>name <span style="color: blue">in </span>GetStreetNames())
{
    db.Execute(<span style="color: #a31515">&quot;INSERT INTO StreetNames (Name) Values (@Name)&quot;</span>,
        <span style="color: blue">new </span>{ Name = name });
}</pre>
<p>you’ll likely want to grab the data in pages. To get the data as pages, you’ll 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>
<pre class="code"><span style="color: #a31515">OFFSET @offset ROWS
FETCH NEXT @rows ROWS ONLY
</span></pre>
<p>So, using the sample database:</p>
<pre class="code"><span style="color: blue">using </span>(<span style="color: blue">var </span>db = <span style="color: blue">new </span><span style="color: #2b91af">SqlCeConnection</span>(connectionString))
{
    db.Open();
    <span style="color: blue">for </span>(<span style="color: blue">var </span>group = 0; ; group++)
    {
        <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;== GROUP {0} ==&quot;</span>, group));
        <span style="color: blue">var </span>streets = db.Query&lt;<span style="color: #2b91af">StreetName</span>&gt;(<span style="color: #a31515">@&quot;SELECT * FROM StreetNames
                           ORDER BY Id
                           OFFSET @offset ROWS
                           FETCH NEXT @rows ROWS ONLY&quot;</span>,
                                <span style="color: blue">new </span>{ offset = group * GroupSize, 
                                    rows = GroupSize });

        <span style="color: blue">foreach </span>(<span style="color: blue">var </span>street <span style="color: blue">in </span>streets)
        {
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;{0} ({1})&quot;</span>,
                street.Name, street.Id));
        }
        <span style="color: blue">if </span>(streets.Count() &lt; GroupSize) { <span style="color: blue">break</span>; }
    }
}</pre>
<p>The code loops until it can’t load a full GroupSize.</p>
<pre class="code"><span style="color: blue">const int </span>GroupSize = 8;</pre>
<p>I added an extension method to <a href="http://msdn.microsoft.com/en-us/library/system.data.idbconnection.aspx">IDbConnection</a> to check whether a table exists:</p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">DbExtensions
</span>{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Determines whether the table exists
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name=&quot;connection&quot;&gt;</span><span style="color: green">Existing, opened, database connection</span><span style="color: gray">&lt;/param&gt;
    /// &lt;param name=&quot;tableName&quot;&gt;</span><span style="color: green">The name of the table to test for.</span><span style="color: gray">&lt;/param&gt;
    /// &lt;returns&gt;</span><span style="color: green">True if table exists.</span><span style="color: gray">&lt;/returns&gt;
    </span><span style="color: blue">public static bool </span>TableExists(<span style="color: blue">this </span><span style="color: #2b91af">IDbConnection </span>connection, <span style="color: blue">string </span>tableName)
    {
        <span style="color: #2b91af">Debug</span>.Assert(connection != <span style="color: blue">null</span>);
        <span style="color: #2b91af">Debug</span>.Assert(!<span style="color: blue">string</span>.IsNullOrWhiteSpace(tableName));

        <span style="color: blue">var </span>cmd = connection.CreateCommand();
        cmd.CommandText = <span style="color: #a31515">@&quot;SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
                            WHERE TABLE_NAME=@TableName&quot;</span>;
        <span style="color: blue">var </span>p1 = cmd.CreateParameter();
        p1.DbType = <span style="color: #2b91af">DbType</span>.String;
        p1.ParameterName = <span style="color: #a31515">&quot;TableName&quot;</span>;
        p1.Value = tableName;
        cmd.Parameters.Add(p1);

        <span style="color: blue">var </span>result = cmd.ExecuteScalar();
        <span style="color: blue">return </span>(<span style="color: blue">int</span>)result == 1;
    }
}</pre>
<p>I really like the simple syntax it permits:</p>
<pre class="code"><span style="color: blue">if </span>(!db.TableExists(<span style="color: #a31515">&quot;StreetNames&quot;</span>))</pre>
<p>It’s used like this:</p>
<pre class="code"><span style="color: blue">private static string </span>CreateDatabase()
{
    <span style="color: blue">var </span>connectionString = <span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;DataSource={0}&quot;</span>, <span style="color: #a31515">&quot;test.sdf&quot;</span>);
    <span style="color: #2b91af">SqlCeEngine </span>engine = <span style="color: blue">new </span><span style="color: #2b91af">SqlCeEngine</span>(connectionString);
    <span style="color: blue">try
    </span>{
        engine.CreateDatabase();
    }
    <span style="color: blue">catch </span>(<span style="color: #2b91af">SqlCeException </span>ex)
    {
        <span style="color: green">// file exists? (if so, we'll just ignore it ...)
        </span><span style="color: blue">if </span>(ex.NativeError != 25114) { <span style="color: blue">throw</span>; }
    }

    <span style="color: blue">using </span>(<span style="color: #2b91af">IDbConnection </span>db = <span style="color: blue">new </span><span style="color: #2b91af">SqlCeConnection</span>(connectionString))
    {
        db.Open();
        <span style="color: green">// create a sample table 
        </span><span style="color: blue">if </span>(!db.TableExists(<span style="color: #a31515">&quot;StreetNames&quot;</span>))
        {
            db.Execute(<span style="color: #a31515">@&quot;CREATE TABLE StreetNames (                
                        Id int IDENTITY NOT NULL,
                        Name nvarchar(24) NOT NULL,
                        CONSTRAINT pk_id PRIMARY KEY (Id))&quot;</span>);
            <span style="color: blue">foreach </span>(<span style="color: blue">var </span>name <span style="color: blue">in </span>GetStreetNames())
            {
                db.Execute(<span style="color: #a31515">&quot;INSERT INTO StreetNames (Name) Values (@Name)&quot;</span>,
                    <span style="color: blue">new </span>{ Name = name });
            }
        }
    }
    <span style="color: blue">return </span>connectionString;
}</pre>
<p>Oddly, Sql Compact doesn’t throw proper (specific) exceptions, so you’ll be forced to check for NativeErrors or against strings rather than specific Exception types. (Seriously!)</p>
<p>Using the <a href="http://msdn.microsoft.com/en-us/library/system.data.sqlserverce.sqlceengine.aspx">SqlCeEngine</a> class, the code attempts to create a new Database file. If it already exists, it throws an exception. All but the file exists exception are rethrown. </p>
<p>Using an open connection and the TableExists extension, it creates a sample table called StreetNames, populated with this data:</p>
<pre class="code"><span style="color: blue">private static </span><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt; GetStreetNames()
{
    <span style="color: green">// Most common street names in UK, apparently :)
    </span><span style="color: blue">yield return </span><span style="color: #a31515">&quot;High Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Station Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Main Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Church Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Victoria Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Park Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Church Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;London Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Manor Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;New Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Park Avenue&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Queens Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Kings Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Church Lane&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Green Lane&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Alexandra Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;The Crescent&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;George Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Grange Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Main Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;King Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;The Avenue&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;New Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;North Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Victoria Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;West Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Queen Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Springfield Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Stanley Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Albert Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Albert Street&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Park Lane&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Chapel Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Highfield Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;The Green&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Mill Lane&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Broadway&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;St. Johns Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Marlborough Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Windsor Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Forest Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;South Street&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Warwick Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Grove Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Kingsway&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;York Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Woodlands Road&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Clarence Road&quot;</span>;
    <span style="color: blue">yield return </span><span style="color: #a31515">&quot;School Lane&quot;</span>; <span style="color: blue">yield return </span><span style="color: #a31515">&quot;Cromwell Road&quot;</span>;
}</pre>
<p><em>(I’d wanted to use the top 50 USA street names, but they’re far more boring as they’re like: Fourth Street, Fifth Street, Oak Street. <img style="border-bottom-style: none; border-left-style: none; border-top-style: none; border-right-style: none" class="wlEmoticon wlEmoticon-smile" alt="Smile" src="blog/wpcontent/uploads/2012/04/wlEmoticon-smile.png" /> ).</em></p>
<p>There’s a tiny class to represent a StreetName that’s used later by the Dapper extension functions:</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">StreetName
</span>{
    <span style="color: blue">public int </span>Id { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
    <span style="color: blue">public string </span>Name { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }
}</pre>
<p>The full main function:</p>
<pre class="code"><span style="color: blue">static void </span>Main(<span style="color: blue">string</span>[] args)
{
    <span style="color: blue">const int </span>GroupSize = 8;

    <span style="color: blue">var </span>connectionString = CreateDatabase();
    <span style="color: blue">using </span>(<span style="color: blue">var </span>db = <span style="color: blue">new </span><span style="color: #2b91af">SqlCeConnection</span>(connectionString))
    {
        db.Open();
        <span style="color: blue">for </span>(<span style="color: blue">var </span>group = 0; ; group++)
        {
            <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;== GROUP {0} ==&quot;</span>, group));
            <span style="color: blue">var </span>streets = db.Query&lt;<span style="color: #2b91af">StreetName</span>&gt;(<span style="color: #a31515">@&quot;SELECT * FROM StreetNames
                               ORDER BY Id
                               OFFSET @offset ROWS
                               FETCH NEXT @rows ROWS ONLY&quot;</span>,
                                    <span style="color: blue">new </span>{ offset = group * GroupSize, 
                                        rows = GroupSize });

            <span style="color: blue">foreach </span>(<span style="color: blue">var </span>street <span style="color: blue">in </span>streets)
            {
                <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: blue">string</span>.Format(<span style="color: #a31515">&quot;{0} ({1})&quot;</span>,
                    street.Name, street.Id));
            }
            <span style="color: blue">if </span>(streets.Count() &lt; GroupSize) { <span style="color: blue">break</span>; }
        }
    }

    <span style="color: #2b91af">Console</span>.WriteLine(<span style="color: #a31515">&quot;** Done **&quot;</span>);
    <span style="color: #2b91af">Console</span>.ReadKey();
}</pre>
<p>The db.Query&lt;StreetName&gt; function is Dapper provided. Given the type and a Query, it automatically and efficiently constructs/deserializes objects of type StreetName for each row returned from the SQL query.</p>
<p>While the syntax isn’t quite as slick as&#160; “Entity Framework” by any means, the resulting run-time efficiency far makes up for that as far as I’m concerned (and if you care about performance, you might want to re-evaluate your use of the EntityFramework as well).</p>
<p>I took the photo above years ago at the <a href="http://www.museumofflight.org/">Boeing Museum of Flight</a> in Seattle (which inspired me to look for videos). For fun, check out this video of a <strong>model</strong> SR-71 blackbird. It takes off around 2:21.</p>
<div style="padding-bottom: 0px; padding-left: 0px; width: 448px; padding-right: 0px; display: block; float: none; margin-left: auto; margin-right: auto; padding-top: 0px" id="scid:5737277B-5D6D-4f48-ABFC-DD9C333F4C5D:e65c08a5-957f-4a42-85e1-e3ccd0d16913" class="wlWriterEditableSmartContent">
<div><object width="448" height="252"><param name="movie" value="http://www.youtube.com/v/SDbQ5xvsrIU?hl=en&amp;hd=1"></param></object></div>
<div style="width:448px;clear:both;font-size:.8em">Model SR-71 Blackbird in flight.</div>
</div>
]]></content:encoded>
					
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1597</post-id>	</item>
	</channel>
</rss>
