<?xml version="1.0" encoding="utf-8"?>
<rss xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:pingback="http://madskills.com/public/xml/rss/module/pingback/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" version="2.0">
  <channel>
    <title>Dot Net What Not - Linq</title>
    <link>http://dotnetwhatnot.pixata.co.uk/</link>
    <description>My rambling thoughts on exploring the .NET framework and related technologies</description>
    <language>en-gb</language>
    <copyright>AY Silver</copyright>
    <lastBuildDate>Wed, 05 Oct 2011 17:14:00 GMT</lastBuildDate>
    <generator>newtelligence dasBlog 2.3.9074.18820</generator>
    <managingEditor>dasblog@example.com</managingEditor>
    <webMaster>dasblog@example.com</webMaster>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=35805926-c217-4269-8ba3-bdf603e4cc93</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,35805926-c217-4269-8ba3-bdf603e4cc93.aspx</pingback:target>
      <dc:creator>AY Silver</dc:creator>
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,35805926-c217-4269-8ba3-bdf603e4cc93.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=35805926-c217-4269-8ba3-bdf603e4cc93</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I previously blogged about a <a title="Click here to read about the seemingly innocent LINQ problem that had us baffled for ages" href="http://dotnetwhatnot.pixata.co.uk/2011/01/23/SeeminglyInnocentLinqProblemThatHadUsBaffledForAges.aspx" target="_blank">seemingly
innocent LINQ problem that had us baffled for ages</a>, which was how you sort or
filter an entity’s child collection in Linq. For example, if you want to pull a collection
of customers, and include all of their orders from this year, but none from earlier,
then there doesn’t seem to be a simple way to do this in Linq. You need to do the
query in two stages, the first which builds an anonymous type, and the second which
links the to parts of it together. See that post for more details.
</p>
        <p>
I also blogged about the problem of <a title="Click here to read my blog post about Linq not including child entities when doing joins" href="http://dotnetwhatnot.pixata.co.uk/2011/05/10/HowToPersuadeALinqQueryToIncludeYourChildObjects.aspx" target="_blank">Linq
not including child entities when doing joins</a>, which requires you to cast the
query to an ObjectQuery&lt;&gt; so you can use the Include() method on it.
</p>
        <p>
The problem comes when you want to combine the two methods, meaning that your query
needs to be constructed in two stages to ensure that the sorting or filtering of the
child collection is done correctly, but you also need to cast the final result to
an ObjectQuery&lt;&gt; before you send it out over WCF. The problem arises because
you need to enumerate the query before doing the Include(), as that is the only way
to ensure that the sorting is done, but calling AsEnumerable() gives you an IEnumerable&lt;&gt;
(reasonably enough), which can't be cast to an ObjectQuery! So what's a fellow to
do? Good question, and one that had me going for ages.
</p>
        <p>
The only way I have found top do this is to enumerate the collection manually. I added
a foreach loop that went through the parent collection and enumerated the children
as it went along. I used Debug.Writeline() to dump the results to the Output window,
which is one of my favourite debugging techniques. Anyone looking at the code would
logically assume that this loop could be removed for the production code (which is
I think what happened when I first wrote it), but this would cause the sorting to
fail.
</p>
        <p>
I ended up with code like that shown below (read to the end of this blog post to see
an improved version of this code). You don’t need to know what the entities represent,
just that I wanted a collection of DhrTemplates, each of which has a number of DhrTemplatesPart
entities, and these had to be sorted on the DisplayPosition property.
</p>
        <!-- code formatted by http://manoli.net/csharpformat/ -->
        <div class="csharpcode">
          <pre class="alt">
            <span class="lnum"> 1: </span>var dhrTemplatesVar = from dt <span class="kwrd">in</span> getContext().DhrTemplates</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">where</span> dt.CurrentTemplate</pre>
          <pre class="alt">
            <span class="lnum"> 3: </span> select <span class="kwrd">new</span> {</pre>
          <pre>
            <span class="lnum"> 4: </span> currentTemplate = dt,</pre>
          <pre class="alt">
            <span class="lnum"> 5: </span> templateParts = dt.DhrTemplatesParts.OrderBy(dtp
=&gt; dtp.DisplayPosition)</pre>
          <pre>
            <span class="lnum"> 6: </span> };</pre>
          <pre class="alt">
            <span class="lnum"> 7: </span>Debug.WriteLine(<span class="str">"Enumerating
the collections..."</span>);</pre>
          <pre>
            <span class="lnum"> 8: </span>
            <span class="kwrd">foreach</span> (var dtmpl <span class="kwrd">in</span> dhrTemplatesVar)
{</pre>
          <pre class="alt">
            <span class="lnum"> 9: </span> DhrTemplate dt = dtmpl.currentTemplate;</pre>
          <pre>
            <span class="lnum"> 10: </span> Debug.WriteLine(<span class="str">"PartDefinitionID:
"</span> + dt.PartDefinitionID);</pre>
          <pre class="alt">
            <span class="lnum"> 11: </span> IOrderedEnumerable&lt;DhrTemplatesPart&gt;
parts = dtmpl.templateParts;</pre>
          <pre>
            <span class="lnum"> 12: </span>
            <span class="kwrd">foreach</span> (DhrTemplatesPart
dtp <span class="kwrd">in</span> parts) {</pre>
          <pre class="alt">
            <span class="lnum"> 13: </span> Debug.WriteLine(<span class="str">"
"</span> + dtp.Description);</pre>
          <pre>
            <span class="lnum"> 14: </span> }</pre>
          <pre class="alt">
            <span class="lnum"> 15: </span>}</pre>
          <pre>
            <span class="lnum"> 16: </span>Debug.WriteLine(<span class="str">" "</span>);</pre>
          <pre class="alt">
            <span class="lnum"> 17: </span>ObjectQuery&lt;DhrTemplate&gt; dhrTemplatesQry
= (from dt <span class="kwrd">in</span> dhrTemplatesVar</pre>
          <pre>
            <span class="lnum"> 18: </span> select dt.currentTemplate) <span class="kwrd">as</span> ObjectQuery&lt;DhrTemplate&gt;;</pre>
          <pre class="alt">
            <span class="lnum"> 19: </span>
            <span class="kwrd">if</span> (dhrTemplatesQry
!= <span class="kwrd">null</span>) {</pre>
          <pre>
            <span class="lnum"> 20: </span> ObjectQuery&lt;DhrTemplate&gt; dhrTemplates =
dhrTemplatesQry</pre>
          <pre class="alt">
            <span class="lnum"> 21: </span> .Include(<span class="str">"User"</span>)</pre>
          <pre>
            <span class="lnum"> 22: </span> .Include(<span class="str">"PartDefinition"</span>)</pre>
          <pre class="alt">
            <span class="lnum"> 23: </span> .Include(<span class="str">"DhrTemplatesParts.PartDefinition.PartInformationTypes"</span>);</pre>
          <pre>
            <span class="lnum"> 24: </span> List&lt;DhrTemplate&gt; dhrTemplatesCurrent =
dhrTemplates.ToList();</pre>
          <pre class="alt">
            <span class="lnum"> 25: </span>
            <span class="kwrd">return</span> dhrTemplatesCurrent;</pre>
          <pre>
            <span class="lnum"> 26: </span>}</pre>
          <pre class="alt">
            <span class="lnum"> 27: </span>
            <span class="kwrd">return</span>
            <span class="kwrd">null</span>;</pre>
        </div>
        <p>
The OrderBy clause on line 5 orders the parts correctly, but isn’t in effect until
the query is enumerated, which is what happens between lines 8 and 15. I don’t actually
need the Debug.WriteLine statements any more, but I left them in case I need to come
back to this again. By the time you get to line 17, you still have the anonymous type
for the query, but now it has been enumerated, so the sorting is done. Now we can
cast it to an ObjectQuery&lt;&gt; and use Include() to include the child entities.
</p>
        <p>
Quite an insidious problem, but obvious when you see the solution. I still have this
feeling that there should be a better way to do it though.
</p>
        <p class="itemBodySubheading">
Update some time later...
</p>
        <p>
Well of course, there was a much better way to do it! Sadly, I was so stuck in the
problem that I missed the blindingly obvious answer. As mentioned, calling AsEnumerable()
enumerates the query, but gives you an IEnumerable&lt;&gt;, which can't be cast to
an ObjectQuery. However, you don’t have to take the returned value from AsEnumerable(),
you can just call it, and carry on using your original query, which has now been enumerated.
</p>
        <p>
This makes the resulting code much simpler...
</p>
        <!-- code formatted by http://manoli.net/csharpformat/ -->
        <div class="csharpcode">
          <pre class="alt">
            <span class="lnum"> 1: </span>var dhrTemplatesVar = from dt <span class="kwrd">in</span> getContext().DhrTemplates</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">where</span> dt.CurrentTemplate</pre>
          <pre class="alt">
            <span class="lnum"> 3: </span> select <span class="kwrd">new</span> {</pre>
          <pre>
            <span class="lnum"> 4: </span> currentTemplate = dt,</pre>
          <pre class="alt">
            <span class="lnum"> 5: </span> templateParts = dt.DhrTemplatesParts.OrderBy(dtp
=&gt; dtp.DisplayPosition)</pre>
          <pre>
            <span class="lnum"> 6: </span> };</pre>
          <pre class="alt">
            <span class="lnum"> 7: </span>dhrTemplatesVar.AsEnumerable();</pre>
          <pre>
            <span class="lnum"> 8: </span>ObjectQuery&lt;DhrTemplate&gt; dhrTemplatesQry
= (from dt <span class="kwrd">in</span> dhrTemplatesVar</pre>
          <pre class="alt">
            <span class="lnum"> 9: </span> select dt.currentTemplate) <span class="kwrd">as</span> ObjectQuery&lt;DhrTemplate&gt;;</pre>
          <pre>
            <span class="lnum"> 10: </span>
            <span class="rem">// rest of the code omitted
as it's identical</span>
          </pre>
        </div>
        <p>
Notice that lines 7 to 16 in the previous listing have been replaced with the single
line 7 in this listing. I’m calling AsEnumerable(), but ignoring the return value.
This enumerates the query, but doesn’t leave me with an ObjectQuery.
</p>
        <p>
Pretty obvious really!
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=35805926-c217-4269-8ba3-bdf603e4cc93" />
      </body>
      <title>Persuading the Entity Framework to sort a child collection part II</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,35805926-c217-4269-8ba3-bdf603e4cc93.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2011/10/05/PersuadingTheEntityFrameworkToSortAChildCollectionPartII.aspx</link>
      <pubDate>Wed, 05 Oct 2011 17:14:00 GMT</pubDate>
      <description>&lt;p&gt;
I previously blogged about a &lt;a title="Click here to read about the seemingly innocent LINQ problem that had us baffled for ages" href="http://dotnetwhatnot.pixata.co.uk/2011/01/23/SeeminglyInnocentLinqProblemThatHadUsBaffledForAges.aspx" target="_blank"&gt;seemingly
innocent LINQ problem that had us baffled for ages&lt;/a&gt;, which was how you sort or
filter an entity’s child collection in Linq. For example, if you want to pull a collection
of customers, and include all of their orders from this year, but none from earlier,
then there doesn’t seem to be a simple way to do this in Linq. You need to do the
query in two stages, the first which builds an anonymous type, and the second which
links the to parts of it together. See that post for more details.
&lt;/p&gt;
&lt;p&gt;
I also blogged about the problem of &lt;a title="Click here to read my blog post about Linq not including child entities when doing joins" href="http://dotnetwhatnot.pixata.co.uk/2011/05/10/HowToPersuadeALinqQueryToIncludeYourChildObjects.aspx" target="_blank"&gt;Linq
not including child entities when doing joins&lt;/a&gt;, which requires you to cast the
query to an ObjectQuery&amp;lt;&amp;gt; so you can use the Include() method on it.
&lt;/p&gt;
&lt;p&gt;
The problem comes when you want to combine the two methods, meaning that your query
needs to be constructed in two stages to ensure that the sorting or filtering of the
child collection is done correctly, but you also need to cast the final result to
an ObjectQuery&amp;lt;&amp;gt; before you send it out over WCF. The problem arises because
you need to enumerate the query before doing the Include(), as that is the only way
to ensure that the sorting is done, but calling AsEnumerable() gives you an IEnumerable&amp;lt;&amp;gt;
(reasonably enough), which can't be cast to an ObjectQuery! So what's a fellow to
do? Good question, and one that had me going for ages.
&lt;/p&gt;
&lt;p&gt;
The only way I have found top do this is to enumerate the collection manually. I added
a foreach loop that went through the parent collection and enumerated the children
as it went along. I used Debug.Writeline() to dump the results to the Output window,
which is one of my favourite debugging techniques. Anyone looking at the code would
logically assume that this loop could be removed for the production code (which is
I think what happened when I first wrote it), but this would cause the sorting to
fail.
&lt;/p&gt;
&lt;p&gt;
I ended up with code like that shown below (read to the end of this blog post to see
an improved version of this code). You don’t need to know what the entities represent,
just that I wanted a collection of DhrTemplates, each of which has a number of DhrTemplatesPart
entities, and these had to be sorted on the DisplayPosition property.
&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt;var dhrTemplatesVar = from dt &lt;span class="kwrd"&gt;in&lt;/span&gt; getContext().DhrTemplates&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;where&lt;/span&gt; dt.CurrentTemplate&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; select &lt;span class="kwrd"&gt;new&lt;/span&gt; {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; currentTemplate = dt,&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 5: &lt;/span&gt; templateParts = dt.DhrTemplatesParts.OrderBy(dtp
=&amp;gt; dtp.DisplayPosition)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 6: &lt;/span&gt; };&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 7: &lt;/span&gt;Debug.WriteLine(&lt;span class="str"&gt;&amp;quot;Enumerating
the collections...&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 8: &lt;/span&gt;&lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var dtmpl &lt;span class="kwrd"&gt;in&lt;/span&gt; dhrTemplatesVar)
{&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 9: &lt;/span&gt; DhrTemplate dt = dtmpl.currentTemplate;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 10: &lt;/span&gt; Debug.WriteLine(&lt;span class="str"&gt;&amp;quot;PartDefinitionID:
&amp;quot;&lt;/span&gt; + dt.PartDefinitionID);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 11: &lt;/span&gt; IOrderedEnumerable&amp;lt;DhrTemplatesPart&amp;gt;
parts = dtmpl.templateParts;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 12: &lt;/span&gt; &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (DhrTemplatesPart
dtp &lt;span class="kwrd"&gt;in&lt;/span&gt; parts) {&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 13: &lt;/span&gt; Debug.WriteLine(&lt;span class="str"&gt;&amp;quot;
&amp;quot;&lt;/span&gt; + dtp.Description);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 14: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 15: &lt;/span&gt;}&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 16: &lt;/span&gt;Debug.WriteLine(&lt;span class="str"&gt;&amp;quot; &amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 17: &lt;/span&gt;ObjectQuery&amp;lt;DhrTemplate&amp;gt; dhrTemplatesQry
= (from dt &lt;span class="kwrd"&gt;in&lt;/span&gt; dhrTemplatesVar&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 18: &lt;/span&gt; select dt.currentTemplate) &lt;span class="kwrd"&gt;as&lt;/span&gt; ObjectQuery&amp;lt;DhrTemplate&amp;gt;;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 19: &lt;/span&gt;&lt;span class="kwrd"&gt;if&lt;/span&gt; (dhrTemplatesQry
!= &lt;span class="kwrd"&gt;null&lt;/span&gt;) {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 20: &lt;/span&gt; ObjectQuery&amp;lt;DhrTemplate&amp;gt; dhrTemplates =
dhrTemplatesQry&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 21: &lt;/span&gt; .Include(&lt;span class="str"&gt;&amp;quot;User&amp;quot;&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 22: &lt;/span&gt; .Include(&lt;span class="str"&gt;&amp;quot;PartDefinition&amp;quot;&lt;/span&gt;)&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 23: &lt;/span&gt; .Include(&lt;span class="str"&gt;&amp;quot;DhrTemplatesParts.PartDefinition.PartInformationTypes&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 24: &lt;/span&gt; List&amp;lt;DhrTemplate&amp;gt; dhrTemplatesCurrent =
dhrTemplates.ToList();&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 25: &lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; dhrTemplatesCurrent;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 26: &lt;/span&gt;}&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 27: &lt;/span&gt;&lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;null&lt;/span&gt;;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The OrderBy clause on line 5 orders the parts correctly, but isn’t in effect until
the query is enumerated, which is what happens between lines 8 and 15. I don’t actually
need the Debug.WriteLine statements any more, but I left them in case I need to come
back to this again. By the time you get to line 17, you still have the anonymous type
for the query, but now it has been enumerated, so the sorting is done. Now we can
cast it to an ObjectQuery&amp;lt;&amp;gt; and use Include() to include the child entities.
&lt;/p&gt;
&lt;p&gt;
Quite an insidious problem, but obvious when you see the solution. I still have this
feeling that there should be a better way to do it though.
&lt;/p&gt;
&lt;p class="itemBodySubheading"&gt;
Update some time later...
&lt;/p&gt;
&lt;p&gt;
Well of course, there was a much better way to do it! Sadly, I was so stuck in the
problem that I missed the blindingly obvious answer. As mentioned, calling AsEnumerable()
enumerates the query, but gives you an IEnumerable&amp;lt;&amp;gt;, which can't be cast to
an ObjectQuery. However, you don’t have to take the returned value from AsEnumerable(),
you can just call it, and carry on using your original query, which has now been enumerated.
&lt;/p&gt;
&lt;p&gt;
This makes the resulting code much simpler...
&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt;var dhrTemplatesVar = from dt &lt;span class="kwrd"&gt;in&lt;/span&gt; getContext().DhrTemplates&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;where&lt;/span&gt; dt.CurrentTemplate&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; select &lt;span class="kwrd"&gt;new&lt;/span&gt; {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; currentTemplate = dt,&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 5: &lt;/span&gt; templateParts = dt.DhrTemplatesParts.OrderBy(dtp
=&amp;gt; dtp.DisplayPosition)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 6: &lt;/span&gt; };&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 7: &lt;/span&gt;dhrTemplatesVar.AsEnumerable();&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 8: &lt;/span&gt;ObjectQuery&amp;lt;DhrTemplate&amp;gt; dhrTemplatesQry
= (from dt &lt;span class="kwrd"&gt;in&lt;/span&gt; dhrTemplatesVar&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="lnum"&gt; 9: &lt;/span&gt; select dt.currentTemplate) &lt;span class="kwrd"&gt;as&lt;/span&gt; ObjectQuery&amp;lt;DhrTemplate&amp;gt;;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 10: &lt;/span&gt;&lt;span class="rem"&gt;// rest of the code omitted
as it's identical&lt;/span&gt;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Notice that lines 7 to 16 in the previous listing have been replaced with the single
line 7 in this listing. I’m calling AsEnumerable(), but ignoring the return value.
This enumerates the query, but doesn’t leave me with an ObjectQuery.
&lt;/p&gt;
&lt;p&gt;
Pretty obvious really!
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=35805926-c217-4269-8ba3-bdf603e4cc93" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,35805926-c217-4269-8ba3-bdf603e4cc93.aspx</comments>
      <category>Entity model framework</category>
      <category>Linq</category>
    </item>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=35b162c7-faf5-430c-83d3-ca5f4a240ca9</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,35b162c7-faf5-430c-83d3-ca5f4a240ca9.aspx</pingback:target>
      <dc:creator>AY Silver</dc:creator>
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,35b162c7-faf5-430c-83d3-ca5f4a240ca9.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=35b162c7-faf5-430c-83d3-ca5f4a240ca9</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p class="itemBodySubheading">
Geographical searches on postcode
</p>
        <p>
I am currently working on an application where I want to have a search feature that
allows people to search for businesses within a certain distance of their home (or
anywhere else they care to choose).
</p>
        <p>
I have some old UK postcode data knocking around, and was going to use that. For those
not familiar with them, UK postcodes are made up of two parts, a major (also known
as “outward”) part, and a minor (or “inward”) part. The major part is one or two letters
followed by one or two digits, and the minor part is a digit, followed by two letters.
Examples of valid postcode formats are M25 0LE, NW11 3ER and L2 3WE (no idea if these
are genuine postcodes though).
</p>
        <p>
Coupled with the postcodes are northings and eastings. These odd-sounding beasties
are simply the number of metres north and east from a designated origin, which is
somewhere west of Lands End. See the <a title="Click here to see a map showing northings and eastings on the Ordinance Survey web site" href="http://www.ordnancesurvey.co.uk/oswebsite/aboutus/reports/misc/calculate.html" rel="nofollow" target="_blank">Ordinance
Survey web site</a> for more details. If you have any two postcodes, you can calculate
the distance between them (as the crow flies) by a simple application of <a title="Click here to read more than you are likely to want to know about Pythagoras’ Theorem" href="http://en.wikipedia.org/wiki/Pythagorean_theorem" rel="nofollow" target="_blank">Pythagoras’
Theorem</a>. My intention was to use all of this in my search code.
</p>
        <p>
Whilst doing some ferreting around the web, looking for more up-to-date data, I found
out that you can now get the UK postcode data absolutely free! When I last looked,
which was some years ago admittedly, they charged an arm and a leg for this. Now all
you need to do is order it from their <a title="Click here to go to the OS downloads page" href="https://www.ordnancesurvey.co.uk/opendatadownload/products.html" rel="nofollow" target="_blank">downloads
page</a>, and you get sent a link to download the data. They have all sorts of interesting
data sets there (including all sorts of maps, street views and so on), but the one
I wanted was the Code-Point Open set. This was far more up-to-date than the data I
had, and was a welcome discovery. Now all I had to do was import it, and write some
calculation code.
</p>
        <p>
Before I got any further though, I further discovered that SQL Server 2008 has a new
data type known as <a title="Click here to read the MSDN article on getting started with the geography data type" href="http://msdn.microsoft.com/en-us/library/bb895266.aspx" rel="nofollow" target="_blank">geography
data</a>, which is used to represent real-world (ie represented on a round Earth)
co-ordinates. It also has the <a title="Click here to read the MSDN article on getting started with the geometry data type" href="http://msdn.microsoft.com/en-us/library/bb895270.aspx" rel="nofollow" target="_blank">geometry
data type</a>, which is a similar idea, but uses a Euclidean (ie flat) co-ordinate
system. Given that I am only dealing with the UK, the curvature of the Earth isn’t
significant in distance calculations, and so either data type would do.
</p>
        <p>
However, converting northings and eastings to geography data isn’t as simple as you
might hope, but I found a post on Adrian Hill’s blog, where he described <a title="Click here to read a blog post on how to convert OS data into geometry data" href="http://www.adathedev.co.uk/2011/01/gb-post-code-geographic-data-load-to.html" rel="nofollow" target="_blank">how
to convert OS data into geometry data</a>, provided a C# console program that does
just that, and then showed how easy it is to query the data for distances between
points. In other words, exactly what I wanted!
</p>
        <p>
I won’t describe the details here, because you can follow that link and read it for
yourself, but basically all you need to do is get the Open-Point data, download the
converter and away you go. Truth be told, it wasn’t quite that simple as the format
of the data has changed slightly since he wrote the code, so I needed to make a small
change. I left a comment on the post, and Adrian updated the code, so you shouldn’t
need to worry about that. It doesn’t use hard-coded column numbers anymore, so should
be future-proof, in case the OS people change the format again.
</p>
        <p class="itemBodySubheading">
Testing the distance calculation, and an important point to improve performance
</p>
        <p>
Once I had the data in SQL Server, I wanted to see how to use it. In the blog post,
Adrian showed a simple piece of SQL that did a sample query. You can see the full
code on his blog, but the main part of it was a call to an SQL Server function named
GeoLocation.STDistance() that did the calculation. He commented that when he tested
it, he searched for postcodes within five miles of his home, and got 8354 rows returned
in around 500ms. I was somewhat surprised when I tried it to discover that it took
around 14 seconds to do a similar calculation! Not exactly what you’d call snappy,
and certainly too slow for a (hopefully) busy application.
</p>
        <p>
I was a bit disappointed with this, but decided that for my purposes, it would be
accurate enough to do the calculation based on the major part of the postcode only.
One of the things Adrian’s code did when importing the data to SQL Server was create
rows where the minor part was blank, and the geography value was an average for the
whole postcode major area. I adjusted my SQL to do this, and I got results quickly
enough that the status bar in SQL Server 2008 Management Studio reported them as zero.
OK, so the results won’t be quite as accurate, but at least they will be fast.
</p>
        <p>
Whilst I was writing this blog post, I looked back at Adrian’s description again,
and noticed one small bullet point that I had missed. When describing what his code
did, he mentioned that it created a spatial index on the geography column. Huh? What
on earth (pardon the pun) is a spatial index. No, I had no idea either, so off I went
to MSDN, and found an article describing <a title="Click here to read the MSDN article on how to create a spatial index" href="http://msdn.microsoft.com/en-us/library/bb964714.aspx" rel="nofollow" target="_blank">how
to create a spatial index</a>. I created one, which took a few minutes (presumably
because there were over 17 million postcodes in the table), and tried again. This
time, I got the performance that Adrian reported. I don’t know if his code really
should have created the spatial index, but it didn’t. However, once it was created,
the execution speed was fast enough for me to use a full postcode search in my application.
</p>
        <p class="itemBodySubheading">
Bringing the code into the Entity Framework model
</p>
        <p>
So, all armed with working code, my next job was to code the search in my application.
This seemed simple enough, just update the Entity Framework model with the new format
of the postcodes table, write some Linq to do the query and we’re done… or not! Sadly,
Entity Framework doesn’t support the geography data type, so it looked like I couldn’t
use my new data! This was a let-down to say the least. Still, not to be put off, I
went off and did some more research, and realised that it was time to learn how to
use stored procedures with Entity Framework. I’d never done this before, simply because
when I discovered Entity Framework, I was so excited by it that I gave up writing
SQL altogether. All my data access code went into the repository classes, and was
written in Linq.
</p>
        <p>
Creating a stored procedure was pretty easy, and was based on Adrian’s sample SQL:
</p>
        <div class="csharpcode">
          <pre class="alt">
            <span class="kwrd">create</span>
            <span class="kwrd">procedure</span> GetPostcodesWithinDistance</pre>
          <pre>@OutwardCode <span class="kwrd">varchar</span>(4),</pre>
          <pre class="alt">@InwardCode <span class="kwrd">varchar</span>(3),</pre>
          <pre>@Miles <span class="kwrd">int</span></pre>
          <pre class="alt">
            <span class="kwrd">as</span>
          </pre>
          <pre>
            <span class="kwrd">begin</span>
          </pre>
          <pre class="alt">
            <span class="kwrd">declare</span> @home geography</pre>
          <pre>
            <span class="kwrd">select</span> @home = GeoLocation <span class="kwrd">from</span> PostCodeData</pre>
          <pre class="alt">
            <span class="kwrd">where</span> OutwardCode = @OutwardCode <span class="kwrd">and</span> InwardCode
= @InwardCode</pre>
          <pre>
            <span class="kwrd">select</span> OutwardCode, InwardCode <span class="kwrd">from</span> dbo.PostCodeData</pre>
          <pre class="alt">
            <span class="kwrd">where</span> GeoLocation.STDistance(@home) &lt;=
(@Miles * 1609)</pre>
          <pre>
            <span class="kwrd">and</span> InwardCode &lt;&gt; <span class="str">''</span></pre>
          <pre class="alt">end</pre>
        </div>
        <p class="itemBodySubheading">
Using stored procedures in Entity Framework
</p>
        <p>
Having coded the stored procedure, I now had to bring it into the Entity Framework
model, and work out how to use it. The first part seemed straightforward enough (doesn’t
it always?). You just refresh your model, open the “Stored Procedures” node in the
tree on the Add tab, select the stored procedure, click OK and you’re done. Or not.
The slight problem was that my fantastic new stored procedure wasn’t actually listed
in the tree on the Add tab. It was a fairly simple case of non-presence (<a title="Click here to see the rather pointless reference to Vic" href="http://www.montypython.net/scripts/phonein.php" rel="nofollow" target="_blank">Vic
wasn’t there either</a>).
</p>
        <p>
After some frustration, someone pointed out to me that it was probably due to the
database user not having execute permission on the stored procedure. Always gets me
that one! Once I had granted execute permission, the stored procedure appeared (although
Vic still wasn’t there), and I was able to bring it into the model. Then I right-clicked
the design surface, chose Add –&gt; Function Import and added the stored procedure
as a function in the model context. Finally I had access to the code in my model,
and could begin to write the search.
</p>
        <p>
Just to ensure that I didn’t get too confident, Microsoft threw another curve-ball
at me at this point. My first attempt at the query looked like this:
</p>
        <!-- code formatted by http://manoli.net/csharpformat/ -->
        <div class="csharpcode">
          <pre class="alt">IEnumerable&lt;<span class="kwrd">string</span>&gt; majors = from
p <span class="kwrd">in</span> jbd.GetPostcodeWithinDistance(<span class="str">"M7"</span>,
45)</pre>
          <pre> </pre>
          <pre class="alt">IQueryable&lt;Business&gt; localBusinesses = from b <span class="kwrd">in</span> ObjSet</pre>
          <pre>
            <span class="kwrd">where</span> (from p <span class="kwrd">in</span> majors</pre>
          <pre class="alt">
            <span class="kwrd">where</span> p.Major == b.PostcodeMajor</pre>
          <pre>                  select p).Count() &gt; 0</pre>
          <pre class="alt">          select b;</pre>
        </div>
        <p>
The first query grabs all the postcodes within 45 miles of the average location of
the major postcode M7.Bear in mind that this query was written before I discovered
the spatial index, so it only uses the major part of the postcode. A later revision
uses the full postcode. The variable jbd is the context, and ObjSet is an ObjectSet&lt;Business&gt;
which is created by my base generic repository.
</p>
        <p>
When this query was executed, I got a delightfully descriptive exception, “<em>Unable
to create a constant value of type 'JBD.Entities.Postcode'. Only primitive types ('such
as Int32, String, and Guid') are supported in this context</em>.” Somewhat baffled,
I turned the Ultimate Source Of All Baffling Problems known as Google, and discovered
that this wasn’t actually the best way to code the query, even if it had worked. I
had forgotten about the Contains() extension method, which was written specifically
for cases like this.
</p>
        <p>
The revised code looked like this (first query omitted as it didn’t change):
</p>
        <!-- code formatted by http://manoli.net/csharpformat/ -->
        <div class="csharpcode">
          <pre class="alt">IQueryable&lt;Business&gt; businesses = from b <span class="kwrd">in</span> ObjSet</pre>
          <pre>
            <span class="kwrd">where</span> majors.Contains(b.PostcodeMajor)</pre>
          <pre class="alt">                                  select b;</pre>
        </div>
        <p>
Somewhat neater, clearer and (more to the point) working!
</p>
        <p>
So, with working code, I now only had more hurdle to jump before I could claim this
one had been cracked.
</p>
        <p>
Copying geography or geometry data to another database
</p>
        <p>
All of the above was going on on my development machine. Now I had working code, I
wanted to put the data on the production server, so that the application could use
it. This turned out to be harder than I thought. I tried the SQL Server Import/Export
wizard, which usually works cleanly enough, but got an error telling me that it couldn’t
convert geography data to geography data. Huh? Searching around for advice, I found
someone who suggested trying to do the copy as NTEXT, NIMAGE, and various other data
types, but none of these worked either.
</p>
        <p>
After some more searching, I discovered <a title="Click here to see the article about this odd error" href="http://www.sql-server-helper.com/sql-server-2008/import-export-unknown-column-type-geography-geometry.aspx" rel="nofollow" target="_blank">an
article describing it</a>, that says that SQL Server has an XML file that contains
definitions for how to convert various data types. Unfortunately, Microsoft seem to
have forgotten to include the geography and geometry data types in there! I found
some code to copy and paste and, lo and behold, it gave the same error message! Ho
hum.
</p>
        <p>
After some more messing around and frustrated attempts, I mentioned the problem to
a friend of mine who came up with the rather simple suggestion of backing up the development
database and attaching it to the SQL Server instance on the production machine. I
had thought of this, but didn’t want to do it as the production database has live
data in it, which would be lost. He pointed out to me that if I attached it under
a different name, I could then copy the data from the newly-attached database to the
production one (which would be very easy now that they were both on the same instance
of SQL Server), and then delete the copy of the development database. Thank you Yaakov!
</p>
        <p>
Thankfully, this all worked fine, and I finally have a working geographic search.
As usual, it was a rough and frustrating ride, but I learned quite a few new things
along the way.
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=35b162c7-faf5-430c-83d3-ca5f4a240ca9" />
      </body>
      <title>The Geography data type in SQL Server 2008 and geographic searches from Entity Framework</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,35b162c7-faf5-430c-83d3-ca5f4a240ca9.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2011/09/20/TheGeographyDataTypeInSQLServer2008AndGeographicSearchesFromEntityFramework.aspx</link>
      <pubDate>Tue, 20 Sep 2011 13:12:00 GMT</pubDate>
      <description>&lt;p class="itemBodySubheading"&gt;
Geographical searches on postcode
&lt;/p&gt;
&lt;p&gt;
I am currently working on an application where I want to have a search feature that
allows people to search for businesses within a certain distance of their home (or
anywhere else they care to choose).
&lt;/p&gt;
&lt;p&gt;
I have some old UK postcode data knocking around, and was going to use that. For those
not familiar with them, UK postcodes are made up of two parts, a major (also known
as “outward”) part, and a minor (or “inward”) part. The major part is one or two letters
followed by one or two digits, and the minor part is a digit, followed by two letters.
Examples of valid postcode formats are M25 0LE, NW11 3ER and L2 3WE (no idea if these
are genuine postcodes though).
&lt;/p&gt;
&lt;p&gt;
Coupled with the postcodes are northings and eastings. These odd-sounding beasties
are simply the number of metres north and east from a designated origin, which is
somewhere west of Lands End. See the &lt;a title="Click here to see a map showing northings and eastings on the Ordinance Survey web site" href="http://www.ordnancesurvey.co.uk/oswebsite/aboutus/reports/misc/calculate.html" rel="nofollow" target="_blank"&gt;Ordinance
Survey web site&lt;/a&gt; for more details. If you have any two postcodes, you can calculate
the distance between them (as the crow flies) by a simple application of &lt;a title="Click here to read more than you are likely to want to know about Pythagoras’ Theorem" href="http://en.wikipedia.org/wiki/Pythagorean_theorem" rel="nofollow" target="_blank"&gt;Pythagoras’
Theorem&lt;/a&gt;. My intention was to use all of this in my search code.
&lt;/p&gt;
&lt;p&gt;
Whilst doing some ferreting around the web, looking for more up-to-date data, I found
out that you can now get the UK postcode data absolutely free! When I last looked,
which was some years ago admittedly, they charged an arm and a leg for this. Now all
you need to do is order it from their &lt;a title="Click here to go to the OS downloads page" href="https://www.ordnancesurvey.co.uk/opendatadownload/products.html" rel="nofollow" target="_blank"&gt;downloads
page&lt;/a&gt;, and you get sent a link to download the data. They have all sorts of interesting
data sets there (including all sorts of maps, street views and so on), but the one
I wanted was the Code-Point Open set. This was far more up-to-date than the data I
had, and was a welcome discovery. Now all I had to do was import it, and write some
calculation code.
&lt;/p&gt;
&lt;p&gt;
Before I got any further though, I further discovered that SQL Server 2008 has a new
data type known as &lt;a title="Click here to read the MSDN article on getting started with the geography data type" href="http://msdn.microsoft.com/en-us/library/bb895266.aspx" rel="nofollow" target="_blank"&gt;geography
data&lt;/a&gt;, which is used to represent real-world (ie represented on a round Earth)
co-ordinates. It also has the &lt;a title="Click here to read the MSDN article on getting started with the geometry data type" href="http://msdn.microsoft.com/en-us/library/bb895270.aspx" rel="nofollow" target="_blank"&gt;geometry
data type&lt;/a&gt;, which is a similar idea, but uses a Euclidean (ie flat) co-ordinate
system. Given that I am only dealing with the UK, the curvature of the Earth isn’t
significant in distance calculations, and so either data type would do.
&lt;/p&gt;
&lt;p&gt;
However, converting northings and eastings to geography data isn’t as simple as you
might hope, but I found a post on Adrian Hill’s blog, where he described &lt;a title="Click here to read a blog post on how to convert OS data into geometry data" href="http://www.adathedev.co.uk/2011/01/gb-post-code-geographic-data-load-to.html" rel="nofollow" target="_blank"&gt;how
to convert OS data into geometry data&lt;/a&gt;, provided a C# console program that does
just that, and then showed how easy it is to query the data for distances between
points. In other words, exactly what I wanted!
&lt;/p&gt;
&lt;p&gt;
I won’t describe the details here, because you can follow that link and read it for
yourself, but basically all you need to do is get the Open-Point data, download the
converter and away you go. Truth be told, it wasn’t quite that simple as the format
of the data has changed slightly since he wrote the code, so I needed to make a small
change. I left a comment on the post, and Adrian updated the code, so you shouldn’t
need to worry about that. It doesn’t use hard-coded column numbers anymore, so should
be future-proof, in case the OS people change the format again.
&lt;/p&gt;
&lt;p class="itemBodySubheading"&gt;
Testing the distance calculation, and an important point to improve performance
&lt;/p&gt;
&lt;p&gt;
Once I had the data in SQL Server, I wanted to see how to use it. In the blog post,
Adrian showed a simple piece of SQL that did a sample query. You can see the full
code on his blog, but the main part of it was a call to an SQL Server function named
GeoLocation.STDistance() that did the calculation. He commented that when he tested
it, he searched for postcodes within five miles of his home, and got 8354 rows returned
in around 500ms. I was somewhat surprised when I tried it to discover that it took
around 14 seconds to do a similar calculation! Not exactly what you’d call snappy,
and certainly too slow for a (hopefully) busy application.
&lt;/p&gt;
&lt;p&gt;
I was a bit disappointed with this, but decided that for my purposes, it would be
accurate enough to do the calculation based on the major part of the postcode only.
One of the things Adrian’s code did when importing the data to SQL Server was create
rows where the minor part was blank, and the geography value was an average for the
whole postcode major area. I adjusted my SQL to do this, and I got results quickly
enough that the status bar in SQL Server 2008 Management Studio reported them as zero.
OK, so the results won’t be quite as accurate, but at least they will be fast.
&lt;/p&gt;
&lt;p&gt;
Whilst I was writing this blog post, I looked back at Adrian’s description again,
and noticed one small bullet point that I had missed. When describing what his code
did, he mentioned that it created a spatial index on the geography column. Huh? What
on earth (pardon the pun) is a spatial index. No, I had no idea either, so off I went
to MSDN, and found an article describing &lt;a title="Click here to read the MSDN article on how to create a spatial index" href="http://msdn.microsoft.com/en-us/library/bb964714.aspx" rel="nofollow" target="_blank"&gt;how
to create a spatial index&lt;/a&gt;. I created one, which took a few minutes (presumably
because there were over 17 million postcodes in the table), and tried again. This
time, I got the performance that Adrian reported. I don’t know if his code really
should have created the spatial index, but it didn’t. However, once it was created,
the execution speed was fast enough for me to use a full postcode search in my application.
&lt;/p&gt;
&lt;p class="itemBodySubheading"&gt;
Bringing the code into the Entity Framework model
&lt;/p&gt;
&lt;p&gt;
So, all armed with working code, my next job was to code the search in my application.
This seemed simple enough, just update the Entity Framework model with the new format
of the postcodes table, write some Linq to do the query and we’re done… or not! Sadly,
Entity Framework doesn’t support the geography data type, so it looked like I couldn’t
use my new data! This was a let-down to say the least. Still, not to be put off, I
went off and did some more research, and realised that it was time to learn how to
use stored procedures with Entity Framework. I’d never done this before, simply because
when I discovered Entity Framework, I was so excited by it that I gave up writing
SQL altogether. All my data access code went into the repository classes, and was
written in Linq.
&lt;/p&gt;
&lt;p&gt;
Creating a stored procedure was pretty easy, and was based on Adrian’s sample SQL:
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;create&lt;/span&gt; &lt;span class="kwrd"&gt;procedure&lt;/span&gt; GetPostcodesWithinDistance&lt;/pre&gt;
&lt;pre&gt;@OutwardCode &lt;span class="kwrd"&gt;varchar&lt;/span&gt;(4),&lt;/pre&gt;
&lt;pre class="alt"&gt;@InwardCode &lt;span class="kwrd"&gt;varchar&lt;/span&gt;(3),&lt;/pre&gt;
&lt;pre&gt;@Miles &lt;span class="kwrd"&gt;int&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;as&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="kwrd"&gt;begin&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="alt"&gt;  &lt;span class="kwrd"&gt;declare&lt;/span&gt; @home geography&lt;/pre&gt;
&lt;pre&gt;  &lt;span class="kwrd"&gt;select&lt;/span&gt; @home = GeoLocation &lt;span class="kwrd"&gt;from&lt;/span&gt; PostCodeData&lt;/pre&gt;
&lt;pre class="alt"&gt;      &lt;span class="kwrd"&gt;where&lt;/span&gt; OutwardCode = @OutwardCode &lt;span class="kwrd"&gt;and&lt;/span&gt; InwardCode
= @InwardCode&lt;/pre&gt;
&lt;pre&gt;  &lt;span class="kwrd"&gt;select&lt;/span&gt; OutwardCode, InwardCode &lt;span class="kwrd"&gt;from&lt;/span&gt; dbo.PostCodeData&lt;/pre&gt;
&lt;pre class="alt"&gt;  &lt;span class="kwrd"&gt;where&lt;/span&gt; GeoLocation.STDistance(@home) &amp;lt;=
(@Miles * 1609)&lt;/pre&gt;
&lt;pre&gt;    &lt;span class="kwrd"&gt;and&lt;/span&gt; InwardCode &amp;lt;&amp;gt; &lt;span class="str"&gt;''&lt;/span&gt;&lt;/pre&gt;
&lt;pre class="alt"&gt;end&lt;/pre&gt;
&lt;/div&gt;
&lt;p class="itemBodySubheading"&gt;
Using stored procedures in Entity Framework
&lt;/p&gt;
&lt;p&gt;
Having coded the stored procedure, I now had to bring it into the Entity Framework
model, and work out how to use it. The first part seemed straightforward enough (doesn’t
it always?). You just refresh your model, open the “Stored Procedures” node in the
tree on the Add tab, select the stored procedure, click OK and you’re done. Or not.
The slight problem was that my fantastic new stored procedure wasn’t actually listed
in the tree on the Add tab. It was a fairly simple case of non-presence (&lt;a title="Click here to see the rather pointless reference to Vic" href="http://www.montypython.net/scripts/phonein.php" rel="nofollow" target="_blank"&gt;Vic
wasn’t there either&lt;/a&gt;).
&lt;/p&gt;
&lt;p&gt;
After some frustration, someone pointed out to me that it was probably due to the
database user not having execute permission on the stored procedure. Always gets me
that one! Once I had granted execute permission, the stored procedure appeared (although
Vic still wasn’t there), and I was able to bring it into the model. Then I right-clicked
the design surface, chose Add –&amp;gt; Function Import and added the stored procedure
as a function in the model context. Finally I had access to the code in my model,
and could begin to write the search.
&lt;/p&gt;
&lt;p&gt;
Just to ensure that I didn’t get too confident, Microsoft threw another curve-ball
at me at this point. My first attempt at the query looked like this:
&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;IEnumerable&amp;lt;&lt;span class="kwrd"&gt;string&lt;/span&gt;&amp;gt; majors = from
p &lt;span class="kwrd"&gt;in&lt;/span&gt; jbd.GetPostcodeWithinDistance(&lt;span class="str"&gt;&amp;quot;M7&amp;quot;&lt;/span&gt;,
45)&lt;/pre&gt;
&lt;pre&gt;&amp;#160;&lt;/pre&gt;
&lt;pre class="alt"&gt;IQueryable&amp;lt;Business&amp;gt; localBusinesses = from b &lt;span class="kwrd"&gt;in&lt;/span&gt; ObjSet&lt;/pre&gt;
&lt;pre&gt;          &lt;span class="kwrd"&gt;where&lt;/span&gt; (from p &lt;span class="kwrd"&gt;in&lt;/span&gt; majors&lt;/pre&gt;
&lt;pre class="alt"&gt;                  &lt;span class="kwrd"&gt;where&lt;/span&gt; p.Major == b.PostcodeMajor&lt;/pre&gt;
&lt;pre&gt;                  select p).Count() &amp;gt; 0&lt;/pre&gt;
&lt;pre class="alt"&gt;          select b;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
The first query grabs all the postcodes within 45 miles of the average location of
the major postcode M7.Bear in mind that this query was written before I discovered
the spatial index, so it only uses the major part of the postcode. A later revision
uses the full postcode. The variable jbd is the context, and ObjSet is an ObjectSet&amp;lt;Business&amp;gt;
which is created by my base generic repository.
&lt;/p&gt;
&lt;p&gt;
When this query was executed, I got a delightfully descriptive exception, “&lt;em&gt;Unable
to create a constant value of type 'JBD.Entities.Postcode'. Only primitive types ('such
as Int32, String, and Guid') are supported in this context&lt;/em&gt;.” Somewhat baffled,
I turned the Ultimate Source Of All Baffling Problems known as Google, and discovered
that this wasn’t actually the best way to code the query, even if it had worked. I
had forgotten about the Contains() extension method, which was written specifically
for cases like this.
&lt;/p&gt;
&lt;p&gt;
The revised code looked like this (first query omitted as it didn’t change):
&lt;/p&gt;
&lt;!-- code formatted by http://manoli.net/csharpformat/ --&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;IQueryable&amp;lt;Business&amp;gt; businesses = from b &lt;span class="kwrd"&gt;in&lt;/span&gt; ObjSet&lt;/pre&gt;
&lt;pre&gt;                                  &lt;span class="kwrd"&gt;where&lt;/span&gt; majors.Contains(b.PostcodeMajor)&lt;/pre&gt;
&lt;pre class="alt"&gt;                                  select b;&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Somewhat neater, clearer and (more to the point) working!
&lt;/p&gt;
&lt;p&gt;
So, with working code, I now only had more hurdle to jump before I could claim this
one had been cracked.
&lt;/p&gt;
&lt;p&gt;
Copying geography or geometry data to another database
&lt;/p&gt;
&lt;p&gt;
All of the above was going on on my development machine. Now I had working code, I
wanted to put the data on the production server, so that the application could use
it. This turned out to be harder than I thought. I tried the SQL Server Import/Export
wizard, which usually works cleanly enough, but got an error telling me that it couldn’t
convert geography data to geography data. Huh? Searching around for advice, I found
someone who suggested trying to do the copy as NTEXT, NIMAGE, and various other data
types, but none of these worked either.
&lt;/p&gt;
&lt;p&gt;
After some more searching, I discovered &lt;a title="Click here to see the article about this odd error" href="http://www.sql-server-helper.com/sql-server-2008/import-export-unknown-column-type-geography-geometry.aspx" rel="nofollow" target="_blank"&gt;an
article describing it&lt;/a&gt;, that says that SQL Server has an XML file that contains
definitions for how to convert various data types. Unfortunately, Microsoft seem to
have forgotten to include the geography and geometry data types in there! I found
some code to copy and paste and, lo and behold, it gave the same error message! Ho
hum.
&lt;/p&gt;
&lt;p&gt;
After some more messing around and frustrated attempts, I mentioned the problem to
a friend of mine who came up with the rather simple suggestion of backing up the development
database and attaching it to the SQL Server instance on the production machine. I
had thought of this, but didn’t want to do it as the production database has live
data in it, which would be lost. He pointed out to me that if I attached it under
a different name, I could then copy the data from the newly-attached database to the
production one (which would be very easy now that they were both on the same instance
of SQL Server), and then delete the copy of the development database. Thank you Yaakov!
&lt;/p&gt;
&lt;p&gt;
Thankfully, this all worked fine, and I finally have a working geographic search.
As usual, it was a rough and frustrating ride, but I learned quite a few new things
along the way.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=35b162c7-faf5-430c-83d3-ca5f4a240ca9" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,35b162c7-faf5-430c-83d3-ca5f4a240ca9.aspx</comments>
      <category>Entity model framework</category>
      <category>Linq</category>
      <category>SQL Server</category>
    </item>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515.aspx</pingback:target>
      <dc:creator>AY Silver</dc:creator>
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
When you use Linq to create a query against an entity framework model, a common scenario
is to use the .Include() extension method to make sure that any child objects are
also loaded. This is mainly useful when the results of the query are to be sent over
WCF, where the client is disconnected from the source of the query, and so cannot
go back to the database to pick up any child objects as needed.
</p>
        <p>
This works fine for simple queries, but falls apart when you want to do anything clever,
like joins or shaping.
</p>
        <p>
Without going into details, all you need to do is cast the query to an ObjectQuery&lt;&gt;
and use .Include() on that. The syntax is not as obvious as it might be, so here’s
an example…
</p>
        <pre class="csharpcode">ObjectQuery&lt;Ferret&gt; ferretQuery = ((from f <span class="kwrd">in</span> ctx.Ferrets
select f) <span class="kwrd">as</span> ObjectQuery&lt;Ferret&gt;) .Include(<span class="str">"User"</span>);</pre>
        <p>
This particular example is too simple to require this trick, but I didn’t want to
distract from the syntax of the cast.
</p>
        <p>
I got this trick (after a long time of frustrated scratching of head at some of Microsoft’s
more obscure and less helpful error messages) from <a href="http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx" target="_blank">this
blog post</a>.
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515" />
      </body>
      <title>How to persuade a Linq query to include your child objects</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2011/05/10/HowToPersuadeALinqQueryToIncludeYourChildObjects.aspx</link>
      <pubDate>Tue, 10 May 2011 14:21:00 GMT</pubDate>
      <description>&lt;p&gt;
When you use Linq to create a query against an entity framework model, a common scenario
is to use the .Include() extension method to make sure that any child objects are
also loaded. This is mainly useful when the results of the query are to be sent over
WCF, where the client is disconnected from the source of the query, and so cannot
go back to the database to pick up any child objects as needed.
&lt;/p&gt;
&lt;p&gt;
This works fine for simple queries, but falls apart when you want to do anything clever,
like joins or shaping.
&lt;/p&gt;
&lt;p&gt;
Without going into details, all you need to do is cast the query to an ObjectQuery&amp;lt;&amp;gt;
and use .Include() on that. The syntax is not as obvious as it might be, so here’s
an example…
&lt;/p&gt;
&lt;pre class="csharpcode"&gt;ObjectQuery&amp;lt;Ferret&amp;gt; ferretQuery = ((from f &lt;span class="kwrd"&gt;in&lt;/span&gt; ctx.Ferrets
select f) &lt;span class="kwrd"&gt;as&lt;/span&gt; ObjectQuery&amp;lt;Ferret&amp;gt;) .Include(&lt;span class="str"&gt;&amp;quot;User&amp;quot;&lt;/span&gt;);&lt;/pre&gt;
&lt;p&gt;
This particular example is too simple to require this trick, but I didn’t want to
distract from the syntax of the cast.
&lt;/p&gt;
&lt;p&gt;
I got this trick (after a long time of frustrated scratching of head at some of Microsoft’s
more obscure and less helpful error messages) from &lt;a href="http://blogs.msdn.com/b/alexj/archive/2009/06/02/tip-22-how-to-make-include-really-include.aspx" target="_blank"&gt;this
blog post&lt;/a&gt;.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,f925d3dd-b7cd-43f0-8b5b-fe4cf41a0515.aspx</comments>
      <category>Linq</category>
      <category>WCF</category>
    </item>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=cedc8100-b2e8-4341-aa6a-dc23b400e6f5</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,cedc8100-b2e8-4341-aa6a-dc23b400e6f5.aspx</pingback:target>
      <dc:creator>AY Silver</dc:creator>
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,cedc8100-b2e8-4341-aa6a-dc23b400e6f5.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=cedc8100-b2e8-4341-aa6a-dc23b400e6f5</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I came across an innocent-looking Linq problem the other day that really had me (and
Yossi) baffled for some time.
</p>
        <p>
It's easiest explained using the ubiquitous Northwind database (although just about
any other relational database would probably do). Suppose you want a list of customers
with their orders. Pretty easy eh? You do something like...
</p>
        <pre class="csharpcode">from c <span class="kwrd">in</span> context.Customers.Include(<span class="str">"Orders"</span>)
select c;</pre>
        <p>
As you have included the Orders navigation property, this will include every order
for the customer.
</p>
        <p>
Now, what happens if you only want to include orders from this year? Sounds like a
pretty simple request eh? Well, it isn't! If you were to do this in SQL, you could
simply do something like...
</p>
        <pre class="csharpcode">
          <span class="kwrd">select</span> c.CustomerID, c.CompanyName,
o.OrderDate <span class="kwrd">from</span> Customers <span class="kwrd">as</span> c <span class="kwrd">inner</span><span class="kwrd">join</span> Orders <span class="kwrd">as</span> o <span class="kwrd">on</span> o.CustomerID=c.CustomerID <span class="kwrd">where</span> o.OrderDate
&gt; <span class="str">'1 Apr 1998'</span><span class="kwrd">order</span><span class="kwrd">by</span> CompanyName,
OrderDate</pre>
        <p>
Admittedly, this would return a flat dataset, with one row for each order, but you
could fix this with some data shaping without too much problem.
</p>
        <p>
Now the obvious thought would be to do something like this in Linq...
</p>
        <pre class="csharpcode">from c <span class="kwrd">in</span> context.Customers.Include(<span class="str">"Orders"</span>)
where c.Orders.OrderDate &gt; new DateTime(2011, 1, 1) select c;</pre>
        <p>
The problem is that this won't compile as the Orders collection doesn't have an OrderDate
property. Orders is a collection of Order entities.
</p>
        <p>
Well, this one had us going for ages. I posted a question up in two separate forums
(fora?), and didn't get very far. Finally, a very helpful person posted an answer
that worked.
</p>
        <p>
What you have to do is create a query that creates an anonymous type that includes
the Customer entity, and the Orders that you want. Then you create a second query
that selects just the Customer entities from the first query...
</p>
        <div class="csharpcode">
          <pre class="alt">
            <span class="kwrd">using</span> (NorthwindEntities context = <span class="kwrd">new</span> NorthwindEntities())
{</pre>
          <pre>  context.ContextOptions.LazyLoadingEnabled = <span class="kwrd">false</span>;</pre>
          <pre class="alt">  var customers = from c <span class="kwrd">in</span> context.Customers.Include(<span class="str">"Orders"</span>)</pre>
          <pre>
            <span class="kwrd">where</span> c.CompanyName.StartsWith(<span class="str">"A"</span>)</pre>
          <pre class="alt">                  select <span class="kwrd">new</span> { Customer
= c, Orders = c.Orders.Where(o =&gt; o.OrderDate &gt; <span class="kwrd">new</span> DateTime(1998,
1, 1)) };</pre>
          <pre>  IEnumerable&lt;Customer&gt; customers2 = customers.AsEnumerable().Select(c =&gt; c.Customer);</pre>
          <pre class="alt">}</pre>
        </div>
        <p>
What happens behind the scenes is that the Entity Framework uses relationship fixup
to sort out which Order entities should be included in the query. I'm not 100% clear
hat's going on here, but it works.
</p>
        <p>
Two words of warning here. First, this won't work in the rather excellent <a href="http://www.linqpad.net/" target="_blank">LinqPad</a>,
as it doesn't support fixup. Second, you need to disable lazy loading.
</p>
        <p>
If you want to read more about relationship fixup, see page 345 in <a href="http://www.amazon.co.uk/Programming-Entity-Framework-Julia-Lerman/dp/0596807260/ref=sr_1_1?s=books&amp;ie=UTF8&amp;qid=1295795566&amp;sr=1-1" target="_blank">Programming
Entity Framework</a> by Julia Lerman. I couldn't find a decent explanation of it on-line.
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=cedc8100-b2e8-4341-aa6a-dc23b400e6f5" />
      </body>
      <title>Seemingly innocent Linq problem that had us baffled for ages</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,cedc8100-b2e8-4341-aa6a-dc23b400e6f5.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2011/01/23/SeeminglyInnocentLinqProblemThatHadUsBaffledForAges.aspx</link>
      <pubDate>Sun, 23 Jan 2011 15:15:41 GMT</pubDate>
      <description>&lt;p&gt;
I came across an innocent-looking Linq problem the other day that really had me (and
Yossi) baffled for some time.
&lt;/p&gt;
&lt;p&gt;
It's easiest explained using the ubiquitous Northwind database (although just about
any other relational database would probably do). Suppose you want a list of customers
with their orders. Pretty easy eh? You do something like...
&lt;/p&gt;
&lt;pre class="csharpcode"&gt;from c &lt;span class="kwrd"&gt;in&lt;/span&gt; context.Customers.Include(&lt;span class="str"&gt;&amp;quot;Orders&amp;quot;&lt;/span&gt;)
select c;&lt;/pre&gt;
&lt;p&gt;
As you have included the Orders navigation property, this will include every order
for the customer.
&lt;/p&gt;
&lt;p&gt;
Now, what happens if you only want to include orders from this year? Sounds like a
pretty simple request eh? Well, it isn't! If you were to do this in SQL, you could
simply do something like...
&lt;/p&gt;
&lt;pre class="csharpcode"&gt;&lt;span class="kwrd"&gt;select&lt;/span&gt; c.CustomerID, c.CompanyName,
o.OrderDate &lt;span class="kwrd"&gt;from&lt;/span&gt; Customers &lt;span class="kwrd"&gt;as&lt;/span&gt; c &lt;span class="kwrd"&gt;inner&lt;/span&gt; &lt;span class="kwrd"&gt;join&lt;/span&gt; Orders &lt;span class="kwrd"&gt;as&lt;/span&gt; o &lt;span class="kwrd"&gt;on&lt;/span&gt; o.CustomerID=c.CustomerID &lt;span class="kwrd"&gt;where&lt;/span&gt; o.OrderDate
&amp;gt; &lt;span class="str"&gt;'1 Apr 1998'&lt;/span&gt; &lt;span class="kwrd"&gt;order&lt;/span&gt; &lt;span class="kwrd"&gt;by&lt;/span&gt; CompanyName,
OrderDate&lt;/pre&gt;
&lt;p&gt;
Admittedly, this would return a flat dataset, with one row for each order, but you
could fix this with some data shaping without too much problem.
&lt;/p&gt;
&lt;p&gt;
Now the obvious thought would be to do something like this in Linq...
&lt;/p&gt;
&lt;pre class="csharpcode"&gt;from c &lt;span class="kwrd"&gt;in&lt;/span&gt; context.Customers.Include(&lt;span class="str"&gt;&amp;quot;Orders&amp;quot;&lt;/span&gt;)
where c.Orders.OrderDate &amp;gt; new DateTime(2011, 1, 1) select c;&lt;/pre&gt;
&lt;p&gt;
The problem is that this won't compile as the Orders collection doesn't have an OrderDate
property. Orders is a collection of Order entities.
&lt;/p&gt;
&lt;p&gt;
Well, this one had us going for ages. I posted a question up in two separate forums
(fora?), and didn't get very far. Finally, a very helpful person posted an answer
that worked.
&lt;/p&gt;
&lt;p&gt;
What you have to do is create a query that creates an anonymous type that includes
the Customer entity, and the Orders that you want. Then you create a second query
that selects just the Customer entities from the first query...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre class="alt"&gt;&lt;span class="kwrd"&gt;using&lt;/span&gt; (NorthwindEntities context = &lt;span class="kwrd"&gt;new&lt;/span&gt; NorthwindEntities())
{&lt;/pre&gt;
&lt;pre&gt;  context.ContextOptions.LazyLoadingEnabled = &lt;span class="kwrd"&gt;false&lt;/span&gt;;&lt;/pre&gt;
&lt;pre class="alt"&gt;  var customers = from c &lt;span class="kwrd"&gt;in&lt;/span&gt; context.Customers.Include(&lt;span class="str"&gt;&amp;quot;Orders&amp;quot;&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;                  &lt;span class="kwrd"&gt;where&lt;/span&gt; c.CompanyName.StartsWith(&lt;span class="str"&gt;&amp;quot;A&amp;quot;&lt;/span&gt;)&lt;/pre&gt;
&lt;pre class="alt"&gt;                  select &lt;span class="kwrd"&gt;new&lt;/span&gt; { Customer
= c, Orders = c.Orders.Where(o =&amp;gt; o.OrderDate &amp;gt; &lt;span class="kwrd"&gt;new&lt;/span&gt; DateTime(1998,
1, 1)) };&lt;/pre&gt;
&lt;pre&gt;  IEnumerable&amp;lt;Customer&amp;gt; customers2 = customers.AsEnumerable().Select(c =&amp;gt; c.Customer);&lt;/pre&gt;
&lt;pre class="alt"&gt;}&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
What happens behind the scenes is that the Entity Framework uses relationship fixup
to sort out which Order entities should be included in the query. I'm not 100% clear
hat's going on here, but it works.
&lt;/p&gt;
&lt;p&gt;
Two words of warning here. First, this won't work in the rather excellent &lt;a href="http://www.linqpad.net/" target="_blank"&gt;LinqPad&lt;/a&gt;,
as it doesn't support fixup. Second, you need to disable lazy loading.
&lt;/p&gt;
&lt;p&gt;
If you want to read more about relationship fixup, see page 345 in &lt;a href="http://www.amazon.co.uk/Programming-Entity-Framework-Julia-Lerman/dp/0596807260/ref=sr_1_1?s=books&amp;amp;ie=UTF8&amp;amp;qid=1295795566&amp;amp;sr=1-1" target="_blank"&gt;Programming
Entity Framework&lt;/a&gt; by Julia Lerman. I couldn't find a decent explanation of it on-line.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=cedc8100-b2e8-4341-aa6a-dc23b400e6f5" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,cedc8100-b2e8-4341-aa6a-dc23b400e6f5.aspx</comments>
      <category>Entity model framework</category>
      <category>Linq</category>
    </item>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=a3dac848-1442-42bf-aa31-9a5504127199</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,a3dac848-1442-42bf-aa31-9a5504127199.aspx</pingback:target>
      <dc:creator />
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,a3dac848-1442-42bf-aa31-9a5504127199.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=a3dac848-1442-42bf-aa31-9a5504127199</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
I was working on a RIA service that returned information about scheduled actions.
Amongst the information stored in the database table was the ID of the user who submitted
(actioned) the action, the ID of the user to whom it was assigned (posh grammar eh?),
and the ID of the action type. These IDs were foreign key references to other database
tables.
</p>
        <p>
The problem I had was that I wanted to display the information in an ASP.NET GridView,
and so just wanted the name (title, first name and surname) of the two users, as well
as the description of the action (from the ActionTypes table). A plain old query won't
help here, as all you'll get are the IDs, not the human-readable information.
</p>
        <p>
The obvious way to do this is to include the required information in the query...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span> var actions = from a <span class="kwrd">in</span> ObjectContext.Actions </pre>
          <pre>
            <span class="lnum"> 2: </span> select <span class="kwrd">new</span> { ByUser
= a.ActionedByUser.Firstname, </pre>
          <pre>
            <span class="lnum"> 3: </span> ToUser = a.AssignedToUser.Firstname, </pre>
          <pre>
            <span class="lnum"> 4: </span> a.ActionType.Description };</pre>
        </div>
        <p>
I've only shown those three bits of information in this query, but in reality you
would have other stuff in there as well.
</p>
        <p>
Now this is OK, unless you want to pass the query anywhere. As I discussed in my post
about <a href="http://dotnetwhatnot.pixata.co.uk/2010/08/15/Passing-Custom-And-Anonymous-Types-Across-Code-Boundaries.aspx" target="_blank">passing
custom and anonymous types across code boundaries</a>, once you pass the query out
of code block, you lose the type information.
</p>
        <p>
In that article, we created a utility class that had just the information we wanted.
Here we can't really do that, as we want the objects we handle to fit back into the
RIA service, so the framework can update the database from them. If we simply create
a new class, it won't have the right base type for the RIA service to handle.
</p>
        <p>
The next thought was to make the utility class a subclass of the one the RIA service
understood. That could be done, but was messy, mainly because we then had to modify
every method in the RIA service that used the class. If we had some with the original
class, and some with the subclass, we had exceptions galore.
</p>
        <p>
So, we (Yossi and I, but mainly Yossi!) came up with a brilliantly simple answer.
I have long been a fan of partial classes, mainly because they enable you to split
class code into neat chunks, each in its own file (which probably means my classes
are too big, I know). In this case, we can use the fact that the entity objects are
partial classes, and simple add the required properties to them, without the need
for new classes at all.
</p>
        <p>
All that was needed was the following, embarrassingly simple bit of code...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">partial</span>
            <span class="kwrd">class</span> Action
{</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">string</span> Description
{ get; set; }</pre>
          <pre>
            <span class="lnum"> 3: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">string</span> ByUser
{ get; set; }</pre>
          <pre>
            <span class="lnum"> 4: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">string</span> ToUser
{ get; set; }</pre>
          <pre>
            <span class="lnum"> 5: </span> }</pre>
        </div>
        <p>
This added three new properties to the Action class, but still allowed the RIA service
to use the class as if it hadn't been changed. Then, in the service code, we modified
the query to include the required information. Two steps were needed here, first to
use the Include() extension method to tell the framework to load the navigation objects
that allow you to get at the foreign reference data, and second to add the actual
data.
</p>
        <p>
The original RIA service method call looked like this...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span>
            <span class="kwrd">public</span> IQueryable&lt;Action&gt;
GetActions() {</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">return</span>
            <span class="kwrd">this</span>.ObjectContext.Actions;</pre>
          <pre>
            <span class="lnum"> 3: </span> }</pre>
        </div>
        <p>
...and when we had finished, it looked like this...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span>
            <span class="kwrd">public</span> IQueryable&lt;Action&gt;
GetActions() {</pre>
          <pre>
            <span class="lnum"> 2: </span> var events = <span class="kwrd">this</span>.ObjectContext.Actions</pre>
          <pre>
            <span class="lnum"> 3: </span> .Include(<span class="str">"ActionType"</span>)</pre>
          <pre>
            <span class="lnum"> 4: </span> .Include(<span class="str">"ActionedByUser"</span>)</pre>
          <pre>
            <span class="lnum"> 5: </span> .Include(<span class="str">"AssignedToUser"</span>);</pre>
          <pre>
            <span class="lnum"> 6: </span>
            <span class="kwrd">foreach</span> (Action a <span class="kwrd">in</span> events)
{</pre>
          <pre>
            <span class="lnum"> 7: </span> a.Description = a.ActionType.Description;</pre>
          <pre>
            <span class="lnum"> 8: </span> a.ByUser = a.ActionedByUser.Title</pre>
          <pre>
            <span class="lnum"> 9: </span> + <span class="str">" "</span> + a.ActionedByUser.Firstname
+ <span class="str">" "</span></pre>
          <pre>
            <span class="lnum"> 10: </span> + a.ActionedByUser.Surname;</pre>
          <pre>
            <span class="lnum"> 11: </span> a.ToUser = a.AssignedToUser.Title </pre>
          <pre>
            <span class="lnum"> 12: </span> + <span class="str">" "</span> + a.AssignedToUser.Firstname </pre>
          <pre>
            <span class="lnum"> 13: </span> + <span class="str">" "</span> + a.AssignedToUser.Surname;</pre>
          <pre>
            <span class="lnum"> 14: </span> }</pre>
          <pre>
            <span class="lnum"> 15: </span>
            <span class="kwrd">return</span> events;</pre>
          <pre>
            <span class="lnum"> 16: </span> }</pre>
        </div>
        <p>
You can see the Include() calls on lines 3-5. Having told the framework to include
those navigation objects in the query (they are null by default), we then use a foreach
loop to go through the query, and populate our three new properties. We are actually
including the full names of the users in one field, which we couldn't have done before.
Actually, we could have done it, but it would have been a bit messy. This way is pleasantly
neat.
</p>
        <p>
As long as the code that uses this RIA call knows about the Action type (which it
would need to anyway to use the call), then it should know about the extra properties
we added. This means that it can use the Action objects as normal, and take advantage
of the extra information.
</p>
        <p>
As with many things, once you've found the answer, it's pretty simple.
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=a3dac848-1442-42bf-aa31-9a5504127199" />
      </body>
      <title>Extending entity framework objects that are returned from RIA services</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,a3dac848-1442-42bf-aa31-9a5504127199.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2010/08/15/ExtendingEntityFrameworkObjectsThatAreReturnedFromRIAServices.aspx</link>
      <pubDate>Sun, 15 Aug 2010 17:59:11 GMT</pubDate>
      <description>&lt;p&gt;
I was working on a RIA service that returned information about scheduled actions.
Amongst the information stored in the database table was the ID of the user who submitted
(actioned) the action, the ID of the user to whom it was assigned (posh grammar eh?),
and the ID of the action type. These IDs were foreign key references to other database
tables.
&lt;/p&gt;
&lt;p&gt;
The problem I had was that I wanted to display the information in an ASP.NET GridView,
and so just wanted the name (title, first name and surname) of the two users, as well
as the description of the action (from the ActionTypes table). A plain old query won't
help here, as all you'll get are the IDs, not the human-readable information.
&lt;/p&gt;
&lt;p&gt;
The obvious way to do this is to include the required information in the query...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; var actions = from a &lt;span class="kwrd"&gt;in&lt;/span&gt; ObjectContext.Actions &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; select &lt;span class="kwrd"&gt;new&lt;/span&gt; { ByUser
= a.ActionedByUser.Firstname, &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; ToUser = a.AssignedToUser.Firstname, &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; a.ActionType.Description };&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I've only shown those three bits of information in this query, but in reality you
would have other stuff in there as well.
&lt;/p&gt;
&lt;p&gt;
Now this is OK, unless you want to pass the query anywhere. As I discussed in my post
about &lt;a href="http://dotnetwhatnot.pixata.co.uk/2010/08/15/Passing-Custom-And-Anonymous-Types-Across-Code-Boundaries.aspx" target="_blank"&gt;passing
custom and anonymous types across code boundaries&lt;/a&gt;, once you pass the query out
of code block, you lose the type information.
&lt;/p&gt;
&lt;p&gt;
In that article, we created a utility class that had just the information we wanted.
Here we can't really do that, as we want the objects we handle to fit back into the
RIA service, so the framework can update the database from them. If we simply create
a new class, it won't have the right base type for the RIA service to handle.
&lt;/p&gt;
&lt;p&gt;
The next thought was to make the utility class a subclass of the one the RIA service
understood. That could be done, but was messy, mainly because we then had to modify
every method in the RIA service that used the class. If we had some with the original
class, and some with the subclass, we had exceptions galore.
&lt;/p&gt;
&lt;p&gt;
So, we (Yossi and I, but mainly Yossi!) came up with a brilliantly simple answer.
I have long been a fan of partial classes, mainly because they enable you to split
class code into neat chunks, each in its own file (which probably means my classes
are too big, I know). In this case, we can use the fact that the entity objects are
partial classes, and simple add the required properties to them, without the need
for new classes at all.
&lt;/p&gt;
&lt;p&gt;
All that was needed was the following, embarrassingly simple bit of code...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;partial&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Action
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Description
{ get; set; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; ByUser
{ get; set; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; ToUser
{ get; set; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 5: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
This added three new properties to the Action class, but still allowed the RIA service
to use the class as if it hadn't been changed. Then, in the service code, we modified
the query to include the required information. Two steps were needed here, first to
use the Include() extension method to tell the framework to load the navigation objects
that allow you to get at the foreign reference data, and second to add the actual
data.
&lt;/p&gt;
&lt;p&gt;
The original RIA service method call looked like this...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IQueryable&amp;lt;Action&amp;gt;
GetActions() {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; &lt;span class="kwrd"&gt;this&lt;/span&gt;.ObjectContext.Actions;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
...and when we had finished, it looked like this...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; IQueryable&amp;lt;Action&amp;gt;
GetActions() {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; var events = &lt;span class="kwrd"&gt;this&lt;/span&gt;.ObjectContext.Actions&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; .Include(&lt;span class="str"&gt;"ActionType"&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; .Include(&lt;span class="str"&gt;"ActionedByUser"&lt;/span&gt;)&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 5: &lt;/span&gt; .Include(&lt;span class="str"&gt;"AssignedToUser"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 6: &lt;/span&gt; &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (Action a &lt;span class="kwrd"&gt;in&lt;/span&gt; events)
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 7: &lt;/span&gt; a.Description = a.ActionType.Description;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 8: &lt;/span&gt; a.ByUser = a.ActionedByUser.Title&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 9: &lt;/span&gt; + &lt;span class="str"&gt;" "&lt;/span&gt; + a.ActionedByUser.Firstname
+ &lt;span class="str"&gt;" "&lt;/span&gt;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 10: &lt;/span&gt; + a.ActionedByUser.Surname;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 11: &lt;/span&gt; a.ToUser = a.AssignedToUser.Title &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 12: &lt;/span&gt; + &lt;span class="str"&gt;" "&lt;/span&gt; + a.AssignedToUser.Firstname &lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 13: &lt;/span&gt; + &lt;span class="str"&gt;" "&lt;/span&gt; + a.AssignedToUser.Surname;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 14: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 15: &lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; events;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 16: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
You can see the Include() calls on lines 3-5. Having told the framework to include
those navigation objects in the query (they are null by default), we then use a foreach
loop to go through the query, and populate our three new properties. We are actually
including the full names of the users in one field, which we couldn't have done before.
Actually, we could have done it, but it would have been a bit messy. This way is pleasantly
neat.
&lt;/p&gt;
&lt;p&gt;
As long as the code that uses this RIA call knows about the Action type (which it
would need to anyway to use the call), then it should know about the extra properties
we added. This means that it can use the Action objects as normal, and take advantage
of the extra information.
&lt;/p&gt;
&lt;p&gt;
As with many things, once you've found the answer, it's pretty simple.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=a3dac848-1442-42bf-aa31-9a5504127199" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,a3dac848-1442-42bf-aa31-9a5504127199.aspx</comments>
      <category>Anonymous types</category>
      <category>Entity model framework</category>
      <category>Linq</category>
      <category>RIA services</category>
    </item>
    <item>
      <trackback:ping>http://dotnetwhatnot.pixata.co.uk/Trackback.aspx?guid=b78b2f03-20ac-41ed-94f4-c685ff0f4499</trackback:ping>
      <pingback:server>http://dotnetwhatnot.pixata.co.uk/pingback.aspx</pingback:server>
      <pingback:target>http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,b78b2f03-20ac-41ed-94f4-c685ff0f4499.aspx</pingback:target>
      <dc:creator />
      <wfw:comment>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,b78b2f03-20ac-41ed-94f4-c685ff0f4499.aspx</wfw:comment>
      <wfw:commentRss>http://dotnetwhatnot.pixata.co.uk/SyndicationService.asmx/GetEntryCommentsRss?guid=b78b2f03-20ac-41ed-94f4-c685ff0f4499</wfw:commentRss>
      <body xmlns="http://www.w3.org/1999/xhtml">
        <p>
RIA services, and Linq in general is great for grabbing entity objects. The code is
simple, and you end up with known objects that you can use.
</p>
        <p>
BUT, when you want to deal with anything slightly off the beaten track, it gets a
bit harder. For example, if you have a Linq query that returns an anonymous type,
you can easily manipulate it in the same code block. For example, to take a gratuitously
silly example, if you had a Bird class...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">class</span> Bird
{</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">private</span>
            <span class="kwrd">int</span> m_Weight;</pre>
          <pre>
            <span class="lnum"> 3: </span>
            <span class="kwrd">public</span> Bird(<span class="kwrd">int</span> Weight)
{</pre>
          <pre>
            <span class="lnum"> 4: </span> m_Weight = Weight;</pre>
          <pre>
            <span class="lnum"> 5: </span> }</pre>
          <pre>
            <span class="lnum"> 6: </span> </pre>
          <pre>
            <span class="lnum"> 7: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">int</span> Weight
{</pre>
          <pre>
            <span class="lnum"> 8: </span> get {</pre>
          <pre>
            <span class="lnum"> 9: </span>
            <span class="kwrd">return</span> m_Weight;</pre>
          <pre>
            <span class="lnum"> 10: </span> }</pre>
          <pre>
            <span class="lnum"> 11: </span> set {</pre>
          <pre>
            <span class="lnum"> 12: </span> m_Weight = <span class="kwrd">value</span>;</pre>
          <pre>
            <span class="lnum"> 13: </span> }</pre>
          <pre>
            <span class="lnum"> 14: </span> }</pre>
          <pre>
            <span class="lnum"> 15: </span> </pre>
          <pre>
            <span class="lnum"> 16: </span> }</pre>
        </div>
        <p>
...then you could write a Linq query like this...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span> var someBirds = from b <span class="kwrd">in</span> birds <span class="kwrd">where</span> b.Weight
&gt; 2 select b;</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">foreach</span> (Bird b <span class="kwrd">in</span> someBirds)
{</pre>
          <pre>
            <span class="lnum"> 3: </span> Console.WriteLine(<span class="str">" I weigh
"</span> + b.Weight.ToString() + <span class="str">"Kg"</span>);</pre>
          <pre>
            <span class="lnum"> 4: </span> }</pre>
        </div>
        <p>
...and since you are dealing with objects of type Bird, the compiler can cope happily.
</p>
        <p>
Even if you are dealing with anonymous types, you're OK in the same code block. Imagine
the Bird class had a Name property (amongst others), then you could write code like
this...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span> var someBirds = from b <span class="kwrd">in</span> birds <span class="kwrd">where</span> b.Weight
&gt; 2 select <span class="kwrd">new</span> { Name = b.Name, Weight = b.Weight };</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">foreach</span> (var b <span class="kwrd">in</span> someBirds)
{</pre>
          <pre>
            <span class="lnum"> 3: </span> Console.WriteLine(<span class="str">"My name is
"</span> + b.Name + <span class="str">", and I weigh "</span> + b.Weight.ToString()
+ <span class="str">"Kg"</span>);</pre>
          <pre>
            <span class="lnum"> 4: </span> }</pre>
        </div>
        <p>
Now here, the variable b in the foreach loop is of an anonymous type, but as you're
in the same code block, the compiler knows what it's dealing with.
</p>
        <p>
The problem comes when you want to pass the Linq query to another code block. This
can be as a parameter in a method, or as the result of a RIA service call. Now you
have a problem, as the code on the other side of the block boundary doesn't know what
the type of the query object is. The framework seems to fall apart at this point!
</p>
        <p>
The simplest way (that I've found so far) is to create a utility class that you can
use in the Linq query...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">class</span> TmpBird
{</pre>
          <pre>
            <span class="lnum"> 2: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">int</span> Weight
{ get; set; }</pre>
          <pre>
            <span class="lnum"> 3: </span>
            <span class="kwrd">public</span>
            <span class="kwrd">string</span> Name
{ get; set; }</pre>
          <pre>
            <span class="lnum"> 4: </span> }</pre>
        </div>
        <p>
I called this TmpBird to distinguish it from the normal Bird class. Note that this
class only needs the two properties that this query uses, and we are taking advantage
of C#'s auto-implemented properties, which means we only need to supply the access
modifier, type and name for property. C# creates a private member variable, and codes
up the getter and setter methods.
</p>
        <p>
Now we can change our Linq query to look like this...
</p>
        <div class="csharpcode">
          <pre>
            <span class="lnum"> 1: </span> var someBirds = from b <span class="kwrd">in</span> birds <span class="kwrd">where</span> b.Weight
&gt; 2 select <span class="kwrd">new</span> TmpBird { Name = <span class="str">"Ferret"</span>,
Weight = b.Weight };</pre>
        </div>
        <p>
And everything works fine. As long as the code block that receives the query knows
about the utility class, it can handle the query easily. In particular, code that
uses a RIA service can handle the query sent back.
</p>
        <p>
This has the advantage that you don't have to send back a full entity object if you
don't want. In the above example, we only wanted the weight and name of the bird,
so we could ignore any other properties. In this simple case, there wouldn't have
been any great loss in sending back the whole Bird object, but if you were dealing
with bigger objects, it could make a significant difference.
</p>
        <p>
For example, if you have a User object in your entity model, you may have a large
number of properties. If you wanted to populate a drop-down list with users, so one
could be chosen, you would only want the user ID and name. Instead of throwing around
a collection of full User objects, you could create a light User utility class, and
pass that around instead.
</p>
        <p>
The one disadvantage of this approach is that you can end up with a proliferation
of utility classes. However, if you make each class private to the code block that
uses it, then the issue can be contained. If the query changes, then the code that
uses it would need to know anyway, so updating the utility class isn't such a huge
issue.
</p>
        <img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=b78b2f03-20ac-41ed-94f4-c685ff0f4499" />
      </body>
      <title>Passing custom and anonymous types across code boundaries</title>
      <guid isPermaLink="false">http://dotnetwhatnot.pixata.co.uk/PermaLink,guid,b78b2f03-20ac-41ed-94f4-c685ff0f4499.aspx</guid>
      <link>http://dotnetwhatnot.pixata.co.uk/2010/08/15/PassingCustomAndAnonymousTypesAcrossCodeBoundaries.aspx</link>
      <pubDate>Sun, 15 Aug 2010 17:02:06 GMT</pubDate>
      <description>&lt;p&gt;
RIA services, and Linq in general is great for grabbing entity objects. The code is
simple, and you end up with known objects that you can use.
&lt;/p&gt;
&lt;p&gt;
BUT, when you want to deal with anything slightly off the beaten track, it gets a
bit harder. For example, if you have a Linq query that returns an anonymous type,
you can easily manipulate it in the same code block. For example, to take a gratuitously
silly example, if you had a Bird class...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; Bird
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;private&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; m_Weight;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; Bird(&lt;span class="kwrd"&gt;int&lt;/span&gt; Weight)
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; m_Weight = Weight;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 5: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 6: &lt;/span&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 7: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Weight
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 8: &lt;/span&gt; get {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 9: &lt;/span&gt; &lt;span class="kwrd"&gt;return&lt;/span&gt; m_Weight;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 10: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 11: &lt;/span&gt; set {&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 12: &lt;/span&gt; m_Weight = &lt;span class="kwrd"&gt;value&lt;/span&gt;;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 13: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 14: &lt;/span&gt; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 15: &lt;/span&gt;&amp;nbsp;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 16: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
...then you could write a Linq query like this...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; var someBirds = from b &lt;span class="kwrd"&gt;in&lt;/span&gt; birds &lt;span class="kwrd"&gt;where&lt;/span&gt; b.Weight
&amp;gt; 2 select b;&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (Bird b &lt;span class="kwrd"&gt;in&lt;/span&gt; someBirds)
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; Console.WriteLine(&lt;span class="str"&gt;" I weigh
"&lt;/span&gt; + b.Weight.ToString() + &lt;span class="str"&gt;"Kg"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
...and since you are dealing with objects of type Bird, the compiler can cope happily.
&lt;/p&gt;
&lt;p&gt;
Even if you are dealing with anonymous types, you're OK in the same code block. Imagine
the Bird class had a Name property (amongst others), then you could write code like
this...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; var someBirds = from b &lt;span class="kwrd"&gt;in&lt;/span&gt; birds &lt;span class="kwrd"&gt;where&lt;/span&gt; b.Weight
&amp;gt; 2 select &lt;span class="kwrd"&gt;new&lt;/span&gt; { Name = b.Name, Weight = b.Weight };&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;foreach&lt;/span&gt; (var b &lt;span class="kwrd"&gt;in&lt;/span&gt; someBirds)
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; Console.WriteLine(&lt;span class="str"&gt;"My name is
"&lt;/span&gt; + b.Name + &lt;span class="str"&gt;", and I weigh "&lt;/span&gt; + b.Weight.ToString()
+ &lt;span class="str"&gt;"Kg"&lt;/span&gt;);&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
Now here, the variable b in the foreach loop is of an anonymous type, but as you're
in the same code block, the compiler knows what it's dealing with.
&lt;/p&gt;
&lt;p&gt;
The problem comes when you want to pass the Linq query to another code block. This
can be as a parameter in a method, or as the result of a RIA service call. Now you
have a problem, as the code on the other side of the block boundary doesn't know what
the type of the query object is. The framework seems to fall apart at this point!
&lt;/p&gt;
&lt;p&gt;
The simplest way (that I've found so far) is to create a utility class that you can
use in the Linq query...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;class&lt;/span&gt; TmpBird
{&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 2: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;int&lt;/span&gt; Weight
{ get; set; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 3: &lt;/span&gt; &lt;span class="kwrd"&gt;public&lt;/span&gt; &lt;span class="kwrd"&gt;string&lt;/span&gt; Name
{ get; set; }&lt;/pre&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 4: &lt;/span&gt; }&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
I called this TmpBird to distinguish it from the normal Bird class. Note that this
class only needs the two properties that this query uses, and we are taking advantage
of C#'s auto-implemented properties, which means we only need to supply the access
modifier, type and name for property. C# creates a private member variable, and codes
up the getter and setter methods.
&lt;/p&gt;
&lt;p&gt;
Now we can change our Linq query to look like this...
&lt;/p&gt;
&lt;div class="csharpcode"&gt;
&lt;pre&gt;&lt;span class="lnum"&gt; 1: &lt;/span&gt; var someBirds = from b &lt;span class="kwrd"&gt;in&lt;/span&gt; birds &lt;span class="kwrd"&gt;where&lt;/span&gt; b.Weight
&amp;gt; 2 select &lt;span class="kwrd"&gt;new&lt;/span&gt; TmpBird { Name = &lt;span class="str"&gt;"Ferret"&lt;/span&gt;,
Weight = b.Weight };&lt;/pre&gt;
&lt;/div&gt;
&lt;p&gt;
And everything works fine. As long as the code block that receives the query knows
about the utility class, it can handle the query easily. In particular, code that
uses a RIA service can handle the query sent back.
&lt;/p&gt;
&lt;p&gt;
This has the advantage that you don't have to send back a full entity object if you
don't want. In the above example, we only wanted the weight and name of the bird,
so we could ignore any other properties. In this simple case, there wouldn't have
been any great loss in sending back the whole Bird object, but if you were dealing
with bigger objects, it could make a significant difference.
&lt;/p&gt;
&lt;p&gt;
For example, if you have a User object in your entity model, you may have a large
number of properties. If you wanted to populate a drop-down list with users, so one
could be chosen, you would only want the user ID and name. Instead of throwing around
a collection of full User objects, you could create a light User utility class, and
pass that around instead.
&lt;/p&gt;
&lt;p&gt;
The one disadvantage of this approach is that you can end up with a proliferation
of utility classes. However, if you make each class private to the code block that
uses it, then the issue can be contained. If the query changes, then the code that
uses it would need to know anyway, so updating the utility class isn't such a huge
issue.
&lt;/p&gt;
&lt;img width="0" height="0" src="http://dotnetwhatnot.pixata.co.uk/aggbug.ashx?id=b78b2f03-20ac-41ed-94f4-c685ff0f4499" /&gt;</description>
      <comments>http://dotnetwhatnot.pixata.co.uk/CommentView,guid,b78b2f03-20ac-41ed-94f4-c685ff0f4499.aspx</comments>
      <category>Anonymous types</category>
      <category>Entity model framework</category>
      <category>Linq</category>
      <category>RIA services</category>
    </item>
  </channel>
</rss>