Following my previous question ( LINQ to Entities only supports constructors and initializers without parameters). I still have a question. I just want to understand what is happening and why something works in one case and not in another.
If you want to specify a string parameter (for example, the querystring parameter) in the Linq query for entities, you should use the new Guid (request.querystring ("param")) instead of Guid.parse (request.querystring ("pairs")). Guid.parse will throw an exception because Linq cannot translate this into SQL.
I often use this technique in my code, and it works.
dim lstResult = DB.MyTable.Where(function(f) f.key = new Guid(request.querystring("param"))).toList()
But when I try to create an anonymous type using the Linq query, it throws an exception:
dim lstResult = DB.MyTable.Where(function(f) f.key = new Guid(request.querystring("param"))).Select(function(f) new With { .guid = f.guid, .name = f.name }).toList()
Exception Excluded:
In LINQ for objects
only constructors and initializers without parameters are supported,
What I could (or should) have done was to declare the Guid parameter in advance (and this is probably good practice), and not use it in the request. It will work:
dim myGuid = Guid.parse(request.querystring("param"))
dim lstResult = DB.MyTable.Where(function(f) f.key = myGuid).Select(function(f) new With { .guid = f.guid, .name = f.name }).toList()
So my question is: why did it work without creating anonymous types and why does an exception occur when trying to create anonymous types? What is the mechanism causing this exception?
source
share