Expert wanna be
Expert wanna be

Reputation: 10624

Asp.net c#, Unable to create a constant value of type 'System.Object'

var result = from q in memberDbSet
     select new
     {
         no = q.no,
         fullName = q.firstName + ' ' + q.lastName
     };

Unable to create a constant value of type 'System.Object'. Only primitive types or enumeration types are supported in this context.

I got above error, what am I doing wrong?

Upvotes: 0

Views: 760

Answers (2)

Gert Arnold
Gert Arnold

Reputation: 109185

You are concatenating strings and a char. Apparently, Entity Framework doesn't like that. Change it into

fullName = q.firstName + " " + q.lastName

The only thing is, I would have expected

Unable to create a constant value of type 'System.Char'

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726829

This happens because the LINQ provider cannot translate the q.firstName + ' ' + q.lastName expression to SQL. A work-around for this is to call AsEnumerable() to bring the data in memory, and do the rest of your selection there:

var result = (from q in memberDbSet /* where clause goes here */)
   .AsEnumerable()
   . Select(q => new {
        no = q.no,
        fullName = q.firstName + ' ' + q.lastName
   });

Make sure that you put all filtering into the query prior to AsEnumerable() to avoid reading into memory more data than you need.

Upvotes: 3

Related Questions