.net – LINQ to Entities does not recognize the method System.String

c#-4.0linqlinq-to-entitiesnet

I keep getting this error message from the code below. What am I doing wrong?

LINQ to Entities does not recognize the method 'System.String ToString(System.Object)' method, and this method cannot be translated into a store expression.

var pros = from programs in db.Programs
           select new {
               programs.ProgramID,
              val = (programs.ProgramShortName + " On: " +  (Convert.ToString(programs.ProgramStartDate) ?? ""))
                           };

lbPrograms.DataTextField = "val";
lbPrograms.DataValueField = "ProgramID";
lbPrograms.DataSource = pros;
lbPrograms.DataBind();

Best Answer

It doesn't recognise string Convert.ToString(object)... so... don't use that. You could try .ToString() directly, but frankly I would just select:

...
select new {
          programs.ProgramID,
          programs.ProgramShortName,
          programs.ProgramStartDate }

and worry about any stringification locally. Or at least a separate projection (noting that AsEnumerable() changes this from composition to deferred iteration):

var formatted = from programs in pros.AsEnumberable()
                select new {
                 programs.ProgramID,
                 val = (programs.ProgramShortName
        + " On: " +  (Convert.ToString(programs.ProgramStartDate) ?? "")) };

and then bind to formatted. This will do a query on the 3 columns, but format locally.