Consider the following line of code:
private void DoThis() { int i = 5; var repo = new ReportsRepository<RptCriteriaHint>(); // This does NOT work var query1 = repo.Find(x => x.CriteriaTypeID == i).ToList<RptCriteriaHint>(); // This DOES work var query1 = repo.Find(x => x.CriteriaTypeID == 5).ToList<RptCriteriaHint>(); }
So when I hardwire an actual number into the lambda function, it works fine. When I use a captured variable into the expression it comes back with the following error:
No mapping exists from object type ReportBuilder.Reporter+<>c__DisplayClass0 to a known managed provider native type.
Why? How can I fix it?
Technically, the correct way to fix this is for the framework that is accepting the expression tree from your lambda to evaluate the
ireference; in other words, it’s a LINQ framework limitation for some specific framework. What it is currently trying to do is interpret theias a member access on some type known to it (the provider) from the database. Because of the way lambda variable capture works, theilocal variable is actually a field on a hidden class, the one with the funny name, that the provider doesn’t recognize.So, it’s a framework problem.
If you really must get by, you could construct the expression manually, like this:
… but that’s just masochism.
Your comment on this entry prompts me to explain further.
Lambdas are convertible into one of two types: a delegate with the correct signature, or an
Expression<TDelegate>of the correct signature. LINQ to external databases (as opposed to any kind of in-memory query) works using the second kind of conversion.The compiler converts lambda expressions into expression trees, roughly speaking, by:
Expressionclass so that, at runtime, an object tree is created that faithfully represents the parsed text.LINQ to external data sources is supposed to take this expression tree and interpret it for its semantic content, and interpret symbolic expressions inside the tree as either referring to things specific to its context (e.g. columns in the DB), or immediate values to convert. Usually, System.Reflection is used to look for framework-specific attributes to guide this conversion.
However, it looks like SubSonic is not properly treating symbolic references that it cannot find domain-specific correspondences for; rather than evaluating the symbolic references, it’s just punting. Thus, it’s a SubSonic problem.