Search code examples
c#linqtostring

SQL LINQ Convert to String


How do I convert a dateTime SQL to a string that can be formatted? I have not found a way to convert "requestIniationDate" to a string that can be formatted.

protected void Page_Load(object sender, EventArgs e)
{
    //"data" is a database connection through the Data folder, containing the tables
    var data = new Data.AcademicCodeRequestDBEntities();

    var request = data.Requests.Select(x => new 
                        {
                            x.appName, 
                            x.requestIniatiationDate, 
                            x.status, 
                            x.id
                        }).ToList()
                        .Select(x => new Models.RequestIdentifier() 
                        {
                            id = x.id,
                            appName = x.appName,
                            requestIniatiationDate = x.requestIniatiationDate,
                            status = x.status,

                        });
    editGrid.DataSource = request;
    editGrid.DataBind();
}

Solution

  • According to your comment, requestIniatiationDate and x.requestIniatiationDate are both DateTime. This is the source of your problem as you cannot assign a string to a DateTime.

    A DateTime has no concept of a "format". If you want to display your dates on a page in a specific format you need to use a string to display it. So you need to either modify your RequestIdentifier model to use a string instead of DateTime, or depending on how this is being displayed on the front end you can use a property of the control. For example, if you are using an <asp:boundfield> you can do this:

    <asp:boundfield datafield="requestIniatiationDate" dataformatstring="{0:MMMM d, yyyy}" htmlencode="false" />
    

    Obviously replace with whatever date format you need (you haven't specified).

    Besides that, your Linq statement makes very little sense. You materialize a list, then subsequently .Select() on it.. You select into an anonymous object first for no reason, its all very confusing. You should be able to just do this:

    var request = data.Requests.Select(x => new Models.RequestIdentifier() 
                        {
                            id = x.id,
                            appName = x.appName,
                            requestIniatiationDate = x.requestIniatiationDate,
                            status = x.status,
                        })
                        .ToList();