views:

192

answers:

4

I keep getting an exception about Linq to Entities not supporting certaion query expressions like this:

MyDataContext db = new MyDataContext()
Brand = db.Brands.First(b => b.BrandId == Int32.Parse(brandIdString))

I'm not attempting to pass along the string parsing on to the entity store, I just want to parse that string into an integer for comparison. Is the only work around to do this before hand or am I totally off here?

A: 

Yes. This sucks. I find that you have to do the parsing or normalizing of data outside of the query...then pass in the results. I ran into this when trying to do some date formatting in the bounds of the query. I ended up moving it out of the query into a string variable and then passed in the variable with the proper formatting already applied.

LAME - Entity Framework has a long ways to go!

Andrew Siemer
Odd that I said the same thing as the accepted answer but ended up getting down voted for it! (:P)
Andrew Siemer
Yeah, it's annoying when people downvote without telling you why.
StriplingWarrior
A: 

Can you use this?

MyDataContext db = new MyDataContext();
Brand b = db.Brands.Where(b => b.BrandId == Int32.Parse(brandIdString)).First();

An alternative solution (not using Lambdas...) is this:

MyDataContext db = new MyDataContext();

Brand b = (from Brand b in db.Brands
           where b.BrandId == Int32.Parse(brandIdString)
           select b).First();

(Also, you're missing the ; at the end of each code line, and you haven't specified a variable name for whatever you're getting out of the query, but I suppose those are typos only here...)

Tomas Lycken
Probably still won't work. I'm guessing the framework doesn't have a way to express that in a query when it tries to break the where down. It has to evaluate that as a whole since it's just a bunch of Expressions chained. Were this linq to collections, you'd be fine. That is for the lambdas.
Programmin Tool
Doesn't work either, tried it.
James Alexander
+5  A: 

The best option (at least for the example you gave) is to pull the operation out of your LINQ statement:

Int32 brandId = Int32.Parse(brandIdString)
MyDataContext db = new MyDataContext()
Brand = db.Brands.First(b => b.BrandId == brandId )

Explanation:

When you're using LINQ, it wants to figure out ways to offload as much of the work as it can to your database query. In order to do that, it actually creates an expression tree of all the things you tell it to do in your various lambda expressions. Then when you want to run the query, it decides what SQL statement will be best for doing what you've asked it to do. This allows it to do some very fancy optimization. However, if it doesn't know how to convert something into a SQL statement, it will get mad at you when you try to run the query.

StriplingWarrior
A: 

The database does not exist to serve string parsing needs. Perform the needed parsing before involving it.

David B