Note that there are some explanatory texts on larger screens.

plurals
  1. POLinq to entities: new Guid("") for anonymous type creation vs select
    primarykey
    data
    text
    <p>Following my previous question (<a href="https://stackoverflow.com/questions/16146930/only-parameterless-constructors-and-initializers-are-supported-in-linq-to-entiti/16146972?noredirect=1#comment23072925_16146972">Only parameterless constructors and initializers are supported in LINQ to Entities</a>) I'm still having a question. I just want to understand what is going on and why something works in one case and not another.</p> <p>When you want to cast a string parameter (for example a querystring parameter) in a Linq to entities query, you have to use new Guid(request.querystring("param")) instead of Guid.parse(request.querystring("param")). Guid.parse will throw an exception because Linq cannot translate this into SQL.</p> <p>I'm using this technique often in my code and it works.</p> <pre><code>dim lstResult = DB.MyTable.Where(function(f) f.key = new Guid(request.querystring("param"))).toList() </code></pre> <p>But, when I'm trying to create an anonymous type using a Linq query, it will throw an exception:</p> <pre><code>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() </code></pre> <p>The thrown exception is:</p> <blockquote> <p>Only parameterless constructors and initializers are supported in LINQ to Entities</p> </blockquote> <p>What I could (or should) do is declare the Guid parameter beforehand (and that is maybe good practice) and than using it in the query. It will work:</p> <pre><code>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() </code></pre> <p>So, my question is: why would it work without creating anonymous types and why is the exception raised when trying to create anonymous types? What is the mechanism causing this exception?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload