Long Cloud Technologies
"... A Yankee in the Land of the Long White Cloud, Aotearoa ..."

Linq odd behavior and the need for a .ToList() [where I suspect there shouldn’t be any need]

Give an Entity Frameworks model that has an EmployerUsers table, in which there are two columns, Guid and Name  Consider this code…

List<SelectListItem> employerUserSelectList = new List<SelectListItem>( );

var employerUsers = dal.EmployerUsers.Where( eu => eu.EmployerGuid == SecurityHelpers.EmployerGuid );

employerUserSelectList.Add( new SelectListItem( ) { Text = " [ Select TeamMember ] " , Value = Guid.Empty.ToString( ) } );

employerUserSelectList.AddRange(
   employerUsers.ToList( ).Select(
      eu => new SelectListItem( )
      {
         Text = eu.Name ,
         Value = eu.Guid.ToString( )
      }
   )
);

The important piece of code I want you to really look at is this:

 

employerUsers.ToList( ).Select(
   eu => new SelectListItem( )
   {
      Text = eu.Name ,
      Value = eu.Guid.ToString( )
   }
)

now compare that with this…

employerUsers.Select(
   eu => new SelectListItem( )
   {
      Text = eu.Name ,
      Value = eu.Guid.ToString( )
   }
)

Would you or would you not expect these to both work exactly the same?  Well I would but if you try to run the code with the second clause you get the following error

image

System.NotSupportedException was unhandled by user code
  Message=LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.
  Source=System.Data.Entity
  StackTrace:
		...SNIP...
  InnerException: 

Yeah, pretty weird, you have to add the .ToList() to coalesce the IQueryable into an IEnumerable BEFORE you call the .Select.

I think this is a bug, either the .Select shouldn’t be allowed on the IQueryable if it can’t handle it, or it should be smart enough to do the .ToList() if necessary.

Your Thoughts?

You can reach me on Twitter at @matthewhintzen:  http://twitter.com/matthewhintzen

Posted on 26 Aug 10 22:58 by matthew.hintzen |

Bookmark this post with:

E-mail | Comments(0) | Comment RSS