<?xml version="1.0"?>
<rss version="2.0">
	<channel>
		<title>[LINQ to SQL] System.Linq.Enumerable.ToArray -&gt; System.InvalidOperationException</title>
		<link>http://www.allegro.cc/forums/view/601652</link>
		<description>Allegro.cc Forum Thread</description>
		<webMaster>matthew@allegro.cc (Matthew Leverton)</webMaster>
		<lastBuildDate>Thu, 24 Sep 2009 20:30:30 +0000</lastBuildDate>
	</channel>
	<item>
		<description><![CDATA[<div class="mockup v2"><p>Essentially, I&#39;m querying a database using LINQ, joining a bunch of tables together, and generating an IQueryable of anonymous types from the result. Then, I use the <span class="source-code">IQueryable.Distinct</span> method to remove duplicate records and call <span class="source-code">IEnumerable.AsEnumerable</span> to force it out of SQL and into C#<span class="ref"><sup>[<a href="#">1</a>]</sup></span>. Finally, I call the <span class="source-code">IEnumerable.ToArray</span> method to convert the collection into an array, which will be serialized and sent to the Web client.</p><pre>Type: System.InvalidOperationException
Message: The null value cannot be assigned to a member with type System.Int32
   which is a non-nullable value type.
StackTrace: at Read_&lt;&gt;f__AnonymousType86`10(ObjectMaterializer`1 )
   at System.Data.Linq.SqlClient.ObjectReaderCompiler.ObjectReader`2.MoveNext()
   at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at *snip* in *snip*
   at *snip* in *snip*</pre><p>

<i>(The <tt>*snips*</tt> were to remove code that can be identifying or is otherwise NDA applicable. It was all my own code, the first one being a wrapper that handles exception logging, the second one being the body of a Web method, passed as a <tt>delegate</tt>, that is the source of this problem. Hopefully the remaining anonymous type names aren&#39;t useful to anyone.</i> <img src="http://www.allegro.cc/forums/smileys/lipsrsealed.gif" alt=":-X" /><i>)</i></p><p>I can&#39;t figure out what&#39;s wrong... I&#39;ll make up a query that resembles what I&#39;m doing to give you an idea...</p><div class="source-code"><div class="toolbar"><span class="button numbers"><b>#</b></span><span class="button select">Select</span><span class="button expand">Expand</span></div><div class="inner"><span class="number">  1</span><span class="k1">using</span><span class="k2">(</span>MyDataContext db <span class="k3">=</span> <span class="k1">new</span> MyDataContext<span class="k2">(</span><span class="k2">)</span><span class="k2">)</span>
<span class="number">  2</span><span class="k2">{</span>
<span class="number">  3</span>    var q <span class="k3">=</span> <span class="k2">(</span>from a in db.A
<span class="number">  4</span>             join b in db.B on a.b_id equals b.id
<span class="number">  5</span>             join c in db.C on a.c_id equals c.id into cg
<span class="number">  6</span>             from c in cg.DefaultIfEmpty<span class="k2">(</span><span class="k2">)</span>
<span class="number">  7</span>             from d in db.D on a.d_id equals d.id
<span class="number">  8</span>             from e in db.E on a.e_id equals e.id into eg
<span class="number">  9</span>             from e in eg.DefaultIfEmtpy<span class="k2">(</span><span class="k2">)</span>
<span class="number"> 10</span>             from f in db.F on e.f_id equals f.id into fg
<span class="number"> 11</span>             from f in fg.DefaultIfEmpty<span class="k2">(</span><span class="k2">)</span>
<span class="number"> 12</span>             where a.id <span class="k3">=</span> aid
<span class="number"> 13</span>             <a href="http://www.delorie.com/djgpp/doc/libc/libc_688.html" target="_blank">select</a> <span class="k1">new</span>
<span class="number"> 14</span>             <span class="k2">{</span>
<span class="number"> 15</span>                 b_id <span class="k3">=</span> b.id,
<span class="number"> 16</span>                 g <span class="k3">=</span> b.g,
<span class="number"> 17</span>                 gd <span class="k3">=</span> b.gd<span class="k2">(</span><span class="k2">)</span>,      <span class="c">// The reason I need to get into application</span>
<span class="number"> 18</span>                 ed <span class="k3">=</span> e.d<span class="k2">(</span><span class="k2">)</span>,       <span class="c">//     code is to call application methods.</span>
<span class="number"> 19</span>                 hd <span class="k3">=</span> b.hd<span class="k2">(</span><span class="k2">)</span>,
<span class="number"> 20</span>                 dn <span class="k3">=</span> d.n<span class="k2">(</span><span class="k2">)</span>,
<span class="number"> 21</span>                 f <span class="k3">=</span> f,
<span class="number"> 22</span>                 a_id <span class="k3">=</span> a.id,
<span class="number"> 23</span>                 i <span class="k3">=</span> c.i,
<span class="number"> 24</span>                 j <span class="k3">=</span> <span class="s">"A literal needed to workaround colleague design. :P"</span>
<span class="number"> 25</span>             <span class="k2">}</span><span class="k2">)</span>.Distinct<span class="k2">(</span><span class="k2">)</span>.AsEnumerable<span class="k2">(</span><span class="k2">)</span>.ToArray<span class="k2">(</span><span class="k2">)</span><span class="k2">;</span>
<span class="number"> 26</span>
<span class="number"> 27</span>    <span class="c">/*</span>
<span class="number"> 28</span><span class="c">     * Work with q a little bit. In my particular example, I fetch another similar</span>
<span class="number"> 29</span><span class="c">     * array, and attach both of them to a new anonymous type which is ultimately</span>
<span class="number"> 30</span><span class="c">     * returned to the client (serialized, etc.).</span>
<span class="number"> 31</span><span class="c">     */</span>
<span class="number"> 32</span>
<span class="number"> 33</span>    <span class="k1">return</span> q<span class="k2">;</span>
<span class="number"> 34</span><span class="k2">}</span>
</div></div><p>

Judging from the stack trace above, it seems to be failing in the <span class="source-code">IEnumerable.ToArray</span> method, but I don&#39;t know why it would be. It further suggests that there is conflicting type information, but the anonymous type&#39;s properties come directly from fields in the LINQ entities. The data model was automatically generated by Visual Studio, and to be sure it hadn&#39;t been outdated I just generated it again and still get the same error. All of the fields are nullable with the exception of the record identifier for the main table (in the above example, <span class="source-code">b</span>), which I think should always have a value and can&#39;t be <span class="source-code">null</span> anyway.</p><p>I&#39;m not really sure how to go about debugging this. Unfortunately, the Visual Studio debugger doesn&#39;t seem capable of debugging LINQ and even the extension methods that I&#39;m calling don&#39;t seem to be available in a debug-able form. The code used to work and I don&#39;t know what I did to break it.</p><p>So the question is, why is this exception being thrown and what do I have to do to fix it?</p><p><img src="http://www.allegro.cc/forums/smileys/huh.gif" alt="???" /></p><p><i>** EDIT **</i></p><p>Even if I cast <span class="source-code">b.id</span> to <span class="source-code"><span class="k1">int</span>?</span><span class="ref"><sup>[<a href="#">2</a>]</sup></span> above, making every field in the anonymous type nullable, it still fails the same way.</p><p><i>** EDIT **</i></p><p>After swapping <span class="source-code">IEnumerable.ToArray</span> with <span class="source-code">IEnumerable.ToList</span>, I get the exact same result (the stack trace has a couple of extra methods in there to handle the list, but that&#39;s all).
</p><div class="ref-block"><h2>References</h2><ol><li>I&#39;m still a little if-y when using LINQ about when I&#39;m in SQL and when I&#39;m not so when I&#39;m having problems getting it to work I usually throw something like this in to force it; feel free to correct its usage.</li><li>A short form for <tt>System.Nullable&lt;int&gt;</tt>.</li></ol></div></div>]]>
		</description>
		<author>no-reply@allegro.cc (bamccaig)</author>
		<pubDate>Wed, 23 Sep 2009 00:47:39 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><div class="quote_container"><div class="title"><a href="http://www.allegro.cc/forums/thread/601652/830274#target">bamccaig</a> said:</div><div class="quote"><p>call IEnumerable.AsEnumerable to force it out of SQL and into C#[1]. Finally, I call the IEnumerable.ToArray method to convert the collection into an array</p></div></div><p>
Incorrect. AsEnumerable is only a cast, it does not force evaluation of the query. The ToFoo methods (such as ToArray) do that.</p><p>The fact that it blows up in ToArray just means that something in your query is <span class="cuss"><span>fuck</span></span>ed up. There is no beautiful way to debug it that I know of. You might try turning on .NET source stepping and source server to see if you get a better stack from that, but I bet you already have.</p><p>My suggestion is to split up the query until you figure out where the problem is, making sure to force evaluation at every step of the way.
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (Kibiz0r)</author>
		<pubDate>Wed, 23 Sep 2009 09:45:18 +0000</pubDate>
	</item>
	<item>
		<description><![CDATA[<div class="mockup v2"><div class="quote_container"><div class="title"><a href="http://www.allegro.cc/forums/thread/601652/830324#target">Kibiz0r</a> said:</div><div class="quote"><p>Incorrect. AsEnumerable is only a cast, it does not force evaluation of the query. The ToFoo methods (such as ToArray) do that.</p></div></div><p>
According to the reference document for <a href="http://msdn.microsoft.com/en-us/library/bb335435.aspx"><tt>Enumerable.AsEnumerable</tt></a>, the cast hides custom methods that would otherwise be used.
</p><div class="quote_container"><div class="title"><a href="http://msdn.microsoft.com/en-us/library/bb335435.aspx">Enumerable.AsEnumerable(TSource) Method (System.Linq)</a> said:</div><div class="quote"><p><b>AsEnumerable&lt;(Of &lt;(TSource&gt;)&gt;)(IEnumerable&lt;(Of &lt;(TSource&gt;)&gt;))</b> can be used to choose between query implementations when a sequence implements <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable&lt;(Of &lt;(T&gt;)&gt;)</a> but also has a different set of public query methods available. For example, given a generic class <span class="source-code">Table</span> that implements <a href="http://msdn.microsoft.com/en-us/library/9eekhta0.aspx">IEnumerable&lt;(Of &lt;(T&gt;)&gt;)</a> and has its own methods such as <span class="source-code">Where</span>, <span class="source-code">Select</span>, and <span class="source-code">SelectMany</span>, a call to <span class="source-code">Where</span> would invoke the public <span class="source-code">Where</span> method of <span class="source-code">Table</span>. A <span class="source-code">Table</span> type that represents a database table could have a <span class="source-code">Where</span> method that takes the predicate argument as an expression tree and converts the tree to SQL for remote execution. If remote execution is not desired, for example because the predicate invokes a local method, the <b>AsEnumerable&lt;(Of &lt;(TSource&gt;)&gt;)</b> method can be used to hide the custom methods and instead make the standard query operators available.</p></div></div><p>
<i>(Formatting theirs)</i></p><p>It seems to be saying that in the case of LINQ to SQL, the <span class="source-code">Where</span> method would normally take the resulting expression tree and convert it to SQL, whereas if you call <span class="source-code">AsEnumerable</span> first then it uses the standard implementation.</p><p>I don&#39;t at all claim to be an expert on this. I&#39;m just trying to make sense of it. <img src="http://www.allegro.cc/forums/smileys/lipsrsealed.gif" alt=":-X" /> I don&#39;t think it accomplishes anything in my above example (because the <span class="source-code">ToArray</span> should force it to evaluate in application code anyway), but I think just <span class="source-code">AsEnumerable</span> would work as well.
</p><div class="quote_container"><div class="title"><a href="http://www.allegro.cc/forums/thread/601652/830324#target">Kibiz0r</a> said:</div><div class="quote"><p>You might try turning on .NET source stepping and source server to see if you get a better stack from that, but I bet you already have.</p></div></div><p>
Actually, I hadn&#39;t... <img src="http://www.allegro.cc/forums/smileys/embarassed.gif" alt=":-[" /> The source server thing is prompting me to execute an untrusted command so I&#39;m trying to make sense of it to make sure it isn&#39;t pulling from an untrusted source... <img src="http://www.allegro.cc/forums/smileys/undecided.gif" alt=":-/" />
</p><div class="quote_container"><div class="title"><a href="http://www.allegro.cc/forums/thread/601652/830324#target">Kibiz0r</a> said:</div><div class="quote"><p>My suggestion is to split up the query until you figure out where the problem is, making sure to force evaluation at every step of the way.</p></div></div><p>
This is why I dislike LINQ. It&#39;s a great thing having it integrated directly into the application code, but I find the actual structure of it unintuitive (moreso than SQL) and the tools haven&#39;t advanced to a point where you can debug it. <img src="http://www.allegro.cc/forums/smileys/cry.gif" alt=":&#39;(" /></p><p><i>** EDIT **</i></p><p>I figured it out. It doesn&#39;t really make sense, but at least I figured it out. After letting the overwhelming confusion subside (I spent the better part of yesterday afternoon struggling with Subversion, which was a nice break), I started this morning with a clear head. I started by commenting out columns that were &#39;complex&#39; (i.e., based on the result of methods or property getters). Once I did that, and commented out corresponding <span class="source-code">OrderBy</span> and <span class="source-code">ThenBy</span> calls, the query ran fine. I then started adding them back in the order of least likely to break things to most likely to break things and eventually narrowed it down to a single property.</p><p>The odd thing is, upon investigating the property&#39;s getter, I saw nowhere that <span class="source-code">null</span> could be assigned to an <span class="source-code"><span class="k1">int</span></span>. The property itself was an <span class="source-code"><span class="k1">int</span>?</span> and it either returned <span class="source-code">null</span> or returned an <span class="source-code"><span class="k1">int</span></span> (both completely valid operations). Confused, I lined both the getter and setter with breakpoints and started the debugger. It didn&#39;t get to the breakpoints. I looked again at the query and in the back of my mind remembered that I was left outer joining to that particular table (i.e., <span class="source-code">join x on y into g from x in g.DefaultIfEmpty<span class="k2">(</span><span class="k2">)</span></span>), but I wasn&#39;t checking for <span class="source-code">null</span> before attempting to access properties of the entity (in my mock code above, this was <span class="source-code">c.i</span>). I wrapped it into a ternary operator...</p><div class="source-code snippet"><div class="inner"><pre>...
i <span class="k3">=</span> c <span class="k3">=</span><span class="k3">=</span> null ? null <span class="k2">:</span> c.i,
...
</pre></div></div><p>

...and sure enough the query ran fine with everything uncommented. I would have expected a <span class="source-code">System.NullReferenceException</span> (and I&#39;ve gotten them before). I really can&#39;t explain why it&#39;s throwing <span class="source-code">System.InvalidOperationException</span> based on assigning <span class="source-code">null</span> to an <span class="source-code">System.Int32</span>. <img src="http://www.allegro.cc/forums/smileys/undecided.gif" alt=":-/" /> Anyone?
</p></div>]]>
		</description>
		<author>no-reply@allegro.cc (bamccaig)</author>
		<pubDate>Thu, 24 Sep 2009 20:30:30 +0000</pubDate>
	</item>
</rss>
