[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

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

Posted on 2014-08-10
2
Medium Priority
?
3,342 Views
Last Modified: 2016-10-08
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?
0
Comment
Question by:maqskywalker
2 Comments
 
LVL 64

Accepted Solution

by:
Fernando Soto earned 2000 total points
ID: 40252001
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
 

Expert Comment

by:Niklas Jonsson
ID: 41835304
"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

Featured Post

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

ASP.Net to Oracle Connectivity Recently I had to develop an ASP.NET application connecting to an Oracle database.As I am doing it first time ,I had to solve several problems. This article will help to such developers  to develop an ASP.NET client…
Exception Handling is in the core of any application that is able to dignify its name. In this article, I'll guide you through the process of writing a DRY (Don't Repeat Yourself) Exception Handling mechanism, using Aspect Oriented Programming.
Is your data getting by on basic protection measures? In today’s climate of debilitating malware and ransomware—like WannaCry—that may not be enough. You need to establish more than basics, like a recovery plan that protects both data and endpoints.…
Look below the covers at a subform control , and the form that is inside it. Explore properties and see how easy it is to aggregate, get statistics, and synchronize results for your data. A Microsoft Access subform is used to show relevant calcul…
Suggested Courses
Course of the Month20 days, 10 hours left to enroll

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question