格式化可以为空的DateTime?在包含其他列的查询中

时间:2014-01-27 00:06:22

标签: c# linq linq-to-entities

我有一个WebMethod,它返回特定ProjectID的所有列,效果很好。但是当我返回StartDate列,这是一个DateTime?时,我得到以下返回:/ Date(1391068800000)/。

这是WebMethod:

[WebMethod]
public static object getProjectByID(int id)
{
    using (dbPSREntities7 myEntities = new dbPSREntities7())
    {
        var thisProject = myEntities.tbProjects.Where(x => x.ProjectID == id);

        var columns = thisProject.Select(x => new { x.ProjectContactFirstName, x.ProjectContactLastName, x.refDepartmentID, x.refAuthSignerID, x.ProjectAccountNum, x.ProjectContactInfo, x.refBuildingID, x.ProjectRoomNum, x.ProjectWorkType, x.ProjectDescription, x.ProjectManagerID, x.MaintenanceAccount, x.StartDate }).ToList();

        // I basically want to format x.StartDate correctly
        // and keep it part of the return statement.

        return columns;
    }
}

之前我只能从表中选择一个日期,而不是一个日期与其他一些列相比,我已经能够克服这个问题。这是我只返回一个DateTime的代码?有效的专栏:

[WebMethod]
public static object getBreadCrumbDate(int projectID, int statusID)
{
    using (dbPSREntities7 myEntities = new dbPSREntities7())
    {
        var thisId = myEntities.tbBreadCrumbs.Where(x => x.ProjectID == projectID && x.StatusID == statusID).Max(x => x.BreadCrumbID);
        var columns = myEntities.tbBreadCrumbs
            .Where(x => x.BreadCrumbID == thisId)
            .Select(x => x.CreateDateTime)
            .ToList();

        if (columns.Any())
        {
            var formattedList = columns
                .Select(d => null != d
                    ? d.Value.ToString("MMM dd, yyyy")
                    : string.Empty) // this is just one example to handle null
                .ToList();

            return formattedList;
        }
        else
        {
            return "In Progress";
        }

    }
}

如何将底部代码合并到顶部代码中,以便StartDate作为记录集的一部分返回,但日期格式为“MMM dd yyyy”?

1 个答案:

答案 0 :(得分:0)

在你的第一种方法中:

... x.MaintenanceAccount, x.StartDate, FormattedDate = (x.StartDate.HasValue ? x.StartDate.Value.ToString("MMM dd, yyyy") : String.Empty) }).ToList();

虽然我个人认为格式化仅仅是演示文稿的责任。我不认为您的实体应该带有Date值的格式化表示。