converting a datetime to a string in a Linq to Entities query

Hi experts,

I'm working on a ASP.NET MVC 4 application using C# and Razor Syntax.
I'm using Visual Studio 2013 ultimate and Sql Server 2008.
In my application I'm using the Employees table of the Northwind sql server database.
I'm using the Entity Framework to model the Employees table.
In my controller I have a function that gets the table columns from my model and then returns a JSON list of my data which I then feed this JSON list to a FlexiGrid in my view.

In the Models folder of my MVC application I have a file called All.cs which contains my model this is what I have for my code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;

namespace FlexigridUsingMvc2.Models
{
    public class Employee
    {
        public Int32 EmployeeID { get; set; }
        public string LastName { get; set; }
        public string FirstName { get; set; }
        public string Title { get; set; }
        public string TitleOfCourtesy { get; set; }
        public DateTime BirthDate { get; set; }
        public DateTime HireDate { get; set; }
        public string Address { get; set; }
        public string City { get; set; }
        public string Region { get; set; }
        public string PostalCode { get; set; }
        public string Country { get; set; }
        public string HomePhone { get; set; }

    }

    public class EntContext : DbContext
    {
        public DbSet<Employee> Employees { get; set; }
    }
    

    
}

Open in new window


This is the code I have for my controller called HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlexigridUsingMvc2.Models;

using FlexigridUsingMvc2.Extensions;

namespace FlexigridUsingMvc2.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/



        [HttpPost]
        public JsonResult List(int page, int rp, string qtype, string letter_pressed, string query)
        {

            using (var db = new EntContext())
            {
                if (letter_pressed == "ALL") letter_pressed = "";

                Func<IQueryable<Employee>> EmployeeFiltered = () =>
                    db.Employees
                    .Where(x =>
                            (
                                (
                                    !string.IsNullOrEmpty(letter_pressed)
                                    && x.LastName.StartsWith(letter_pressed)
                                )
                                ||
                                string.IsNullOrEmpty(letter_pressed)
                            )
                            &&
                            (
                                (
                                    !string.IsNullOrEmpty(query)
                                    &&
                                    (
                                        (qtype == "LastName" && x.LastName.Contains(query))
                                        ||
                                        (qtype == "FirstName" && x.FirstName.Contains(query))
                                        ||
                                        (qtype == "Title" && x.Title.Contains(query))
                                        ||
                                        (qtype == "TitleOfCourtesy" && x.TitleOfCourtesy.Contains(query))

                                    )
                                )
                                ||
                                string.IsNullOrEmpty(query)
                            )
                        );
                

                return Json(
                    new
                    {
                        page = page,
                        total = EmployeeFiltered().Count(),
                        rows =
                            EmployeeFiltered()
                            .OrderBy(x => x.LastName)
                            .LimitAndOffset(pageSize: rp, pageOffset: page)
                            .ToList()
                            .Select(x =>
                                new
                                {
                                    id = x.LastName,
                                    cell = new string[] { x.LastName, x.FirstName, x.Title, x.TitleOfCourtesy  }

                                })
                    });


            }//using
        }//List

        public ActionResult Index()
        {
            return View();
        }


    }
}

Open in new window


When I run my application it runs fine and I get this. Notice that all the columns are varchar or char types which I have declared as string type in my Linq to Entities query of my controller.:

flexgrid3.png

So now what I wanted to do was add the column called BirthDate to my grid. In the Employee sql server table this column is of datatype DateTime

So then I changed the code of my controller HomeController.cs to this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using FlexigridUsingMvc2.Models;

using FlexigridUsingMvc2.Extensions;

namespace FlexigridUsingMvc2.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/



        [HttpPost]
        public JsonResult List(int page, int rp, string qtype, string letter_pressed, string query)
        {

            using (var db = new EntContext())
            {
                if (letter_pressed == "ALL") letter_pressed = "";

                Func<IQueryable<Employee>> EmployeeFiltered = () =>
                    db.Employees
                    .Where(x =>
                            (
                                (
                                    !string.IsNullOrEmpty(letter_pressed)
                                    && x.LastName.StartsWith(letter_pressed)
                                )
                                ||
                                string.IsNullOrEmpty(letter_pressed)
                            )
                            &&
                            (
                                (
                                    !string.IsNullOrEmpty(query)
                                    &&
                                    (
                                        (qtype == "LastName" && x.LastName.Contains(query))
                                        ||
                                        (qtype == "FirstName" && x.FirstName.Contains(query))
                                        ||
                                        (qtype == "Title" && x.Title.Contains(query))
                                        ||
                                        (qtype == "TitleOfCourtesy" && x.TitleOfCourtesy.Contains(query))
                                        ||
                                        (qtype == "BirthDate" && x.BirthDate.Contains(query))

                                    )
                                )
                                ||
                                string.IsNullOrEmpty(query)
                            )
                        );
                

                return Json(
                    new
                    {
                        page = page,
                        total = EmployeeFiltered().Count(),
                        rows =
                            EmployeeFiltered()
                            .OrderBy(x => x.LastName)
                            .LimitAndOffset(pageSize: rp, pageOffset: page)
                            .ToList()
                            .Select(x =>
                                new
                                {
                                    id = x.LastName,
                                    // ************** date format 09/19/1937
                                    cell = new string[] { x.LastName, x.FirstName, x.Title, x.TitleOfCourtesy, x.BirthDate.ToString("MM/dd/yyyy") }

                                })
                    });


            }//using
        }//List

        public ActionResult Index()
        {
            return View();
        }


    }
}

Open in new window


But I get this messag on the BirthDate call on my query:
flexgrid1.png
When I try to run my page I get this error message:
flexgrid2.png

The problem is that the BirthDate column is DateTime datatype on my sql server database
So when I'm using in a linq to entities query I need to somehow change it to a string. I heard that I can't use the .ToString() in a linq to entities query.  I tried to write it like this x.BirthDate.ToString().Contains(query)) but it didn't like that.

Since BirthDate is a DateTime datatype how would I convert it to a string in my linq to entities query in my controller?

Anyone know the syntax I need to use to add that BirthDate column to my linq to enties query. How can I convert it from DateTime to string type in my query?
LVL 1
maqskywalkerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Fernando SotoRetiredCommented:
Hi maqskywalker;

This statement is correct, "I heard that I can't use the .ToString() in a linq to entities query.", and this is what the not supported error displayed  by the error message box. If you need it as a string you will need to do it after it is returned from Entity Framework query.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Niklas JonssonCommented:
"If you need it as a string you will need to do it after it is returned from Entity Framework query." - that's not correct though.

You can use SqlFunctions to convert it. It gets a little messy but can prevent getting huge datasets just to convert them - much better to let sql do the converting and filter on that.

Here is how I use it when I need to do a string search on a datetime column in the database (with entityframework):

---
query.Where(x => (SqlFunctions.StringConvert((double)x.CreationTime.Year).Trim() + "-" +
                                        SqlFunctions.Replicate("0", 2 - SqlFunctions.StringConvert((double)x.CreationTime.Month).Trim().Length) + SqlFunctions.StringConvert((double)x.CreationTime.Month).Trim() + "-" +
                                        SqlFunctions.Replicate("0", 2 - SqlFunctions.StringConvert((double)x.CreationTime.Day).Trim().Length) + SqlFunctions.StringConvert((double)x.CreationTime.Day).Trim()).Contains(search));

Open in new window

---

This gets extra messy because I'm correcting the month and day to always be two digits (for example I need to be able to search for "2016-10-08" instead of "2016-10-8".)

Linq to Entities understands SqlFunctions and converts them into correct SQL.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.