Search code examples
c#linq-to-sqlentity-framework-4

Converting a date time field to string in linq


I am trying to convert a datetime field to a string. The error message I got is found below. Have you seen this before? I am not getting a solution. How can I resolve this please?

            public IEnumerable<SelectListItem> GetStatusDate(string strprojectId)
                    {
                        var queryResult = (from dt in _objContext.tbl_Project_Status_MSTR
                            where dt.ProjectID.Equals(strprojectId)
                            orderby dt.ProjectID
                            select new SelectListItem {Text = Convert.ToString(dt.StatusDate),Value = Convert.ToString(dt.StatusDate)});
                        List<SelectListItem> objStatDate = queryResult.ToList();

                        return objStatDate;
                    }

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


Solution

  • One way to do it is to query StatusDate from the database, and then convert it to string in memory like this:

    var objStatDate =
        (from dt in _objContext.tbl_Project_Status_MSTR
        where dt.ProjectID.Equals(strprojectId)
        orderby dt.ProjectID
        select new {dt.StatusDate})
        .ToList() //Execute database query
        .Select(x =>
            new SelectListItem
            {
                Text = Convert.ToString(x.StatusDate), //Convert data in memory
                Value = Convert.ToString(x.StatusDate)
            })
        .ToList();