Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query never returns

I have a simple LINQ-to-EF query that for some reason stopped working, by which I mean that as soon as it is executed, execution control is never returned to the next line. I can't figure out why that may be the case. if I run the same query in LinqPad using LINQ-to-SQL, it works fine. here's the query:

Models.Currency curr = _db.Currencies.SingleOrDefault(x => x.ISO == p.Items[i].CurrType);

where _db is my entity container reference and p.Items[i].CurrType contains the value "USD"

what could be the problem? what kind of diagnostics could I make use of?

TIA - e!

p.s. I'm running on Visual Studio 2013 with MVC5

* update I *

as per the suggestions below, I added both a "Connection Timeout=10" to my connection string (in the Web.config) and a command timeout (in the *.Context.cs) like this:

public partial class Entities : DbContext
{
    public Entities()
        : base("name=Entities")
    {
        ((IObjectContextAdapter)this).ObjectContext.CommandTimeout = 10;
    }

the query still hangs (never times out to throw an exception) and I had a gander at the database whilst the query was hung. I can see that the SQL issued looks (more or less) like:

select * from Currencies

which should return immediately since there are only 100 small records in that table. the connection on which the query gets issued is sleeping and awaiting command, and there is no blocking in the database; the spid in question performed 0 cpu/io.

what else should I be looking at?

like image 969
ekkis Avatar asked Oct 19 '22 15:10

ekkis


1 Answers

a little help from suchiman at freenode's c# channel revealed the problem: I should have been seeing an exception bubble up but I wasn't. he recommended I log my database output like this:

_db.Database.Log = s => System.Diagnostics.Debug.WriteLine(s);

that revealed the error:

A first chance exception of type 'System.NotSupportedException' occurred in EntityFramework.dll Closed connection at 3/17/2015 3:56:43 PM -07:00

from which he cleverly deduced that the reference to p.Items[i].CurrType was messing linq up. here's his reasoning:

[Suchiman] Items[i] is actually a method call
[Suchiman] get_Items(i)
[Suchiman] transformed by the compiler
[Suchiman] when analyzing the expression tree, EF will realize 
[Suchiman] there's a method called get_Items(Int32)
[Suchiman] but it doesn't have any clue how to translate this into SQL
[Suchiman] thats why it throws NotSupportedException

which is proven by the fact that if I rewrite the code like this:

var item = p.Items[i];
var curr = _db.Currencies.SingleOrDefault(x => x.ISO == item.CurrType);

it works!

like image 109
ekkis Avatar answered Nov 03 '22 06:11

ekkis