1

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)

Marc
  • 3,905
  • 4
  • 21
  • 37
Eric
  • 2,273
  • 2
  • 29
  • 44
  • 1
    possible duplicate of [linq to entity framework: use dictionary in query](http://stackoverflow.com/questions/7638859/linq-to-entity-framework-use-dictionary-in-query) – User 12345678 Sep 15 '13 at 23:04

1 Answers1

7

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();
Maxim Balaganskiy
  • 1,524
  • 13
  • 25
  • 3
    I was ready to upvote you until I saw the second part where you gave the option of running the filter after getting ALL records, I would never even want to mention this option to someone who doesn't fully understand the implications. – Timothy Walters Sep 16 '13 at 04:18
  • There are only and only two options: Either fetch all the records and have fully-supported bunch of extension methods or define an intermediate variable. – Alireza Sep 16 '13 at 07:10
  • Tim, the answer is still useful. It gives me the 'why' answer I was looking for plus shows it it's possible but that it's also a bad idea. – Eric Sep 20 '13 at 04:09