Eric
Eric

Reputation: 2283

Why can't I use dictionary["key"] for a where clause in LINQ?

I'm running a simple LINQ query:

var user = (from u in context.Users
          where u.Email == dictionary["email"]
          select u).FirstOrDefault();

When I run that, I get this exception:

LINQ to Entities does not recognize the method 'System.String get_Item(System.String)' method, and this method cannot be translated into a store expression.

If I use an intermediate step of this, it works fine.

String myDictionaryItem = dictionary["email"];

var user = (from u in context.Users
          where u.Email == myDictionaryItem
          select u).FirstOrDefault();

Just seems kind of odd that .Net can't think a little faster to make that connection.

(disclaimer: maybe some typos, I changed some variable names)

Upvotes: 1

Views: 2192

Answers (1)

Maxim Balaganskiy
Maxim Balaganskiy

Reputation: 1574

Linq tries to translate your where clause to SQL and fails because SQL has no dictionaries. Once you give the parser a simple string it is able to produce an SQL statement.

You can make it execute the filter locally, not on the SQL server, but it would hit performance:

var user= (from u in context.Users select u)
    .AsEnumerable()
    .Where(u=>u.Email == dictionary["email"])
    .FirstOrDefault();

Upvotes: 7

Related Questions