Daniel Chernenkov
Daniel Chernenkov

Reputation: 745

Exception in System.Data.Entity.dll but was not handled in user code

I need to count the number of the rows in my database with the entity framework. I am using the LINQ method "Count".

Here is the code:

QvDb dba = new QvDb();
if (dba.KUser.Count(us => us.FacebookId == values["FacebookId"]) == 0)

As you can see the values["FacebookId"] it's a post array variable, and the dba object variable it's the database model builder.

When I am trying to access to the page i got this exception:

An exception of type 'System.NotSupportedException' occurred in System.Data.Entity.dll but was not handled in user code

Additional information: 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.

For the record, the array is not null. It is a string that posted from the form.

Upvotes: 3

Views: 20726

Answers (1)

Matt Houser
Matt Houser

Reputation: 36073

When using LINQ to entities, all parts of your LINQ statement must be supported by the database.

values["FacebookId"] is a local dictionary. So it cannot be executed on the remote SQL database.

Pull the value from the dictionary first into a local variable, then execute your LINQ statement.

QvDb dba = new QvDb();
var id = values["FacebookId"];
if (dba.KUser.Count(us => us.FacebookId == id) == 0)

Upvotes: 5

Related Questions