【问题标题】:Format DateTime object in Model as NotMapped Property将模型中的 DateTime 对象格式化为 NotMapped 属性
【发布时间】:2019-02-26 16:16:24
【问题描述】:

我有一个名为Report 的模型具有以下两个属性。我将检索数据并将其发送到 jQuery 数据表。我需要在将日期字段发送到查看之前对其进行格式化,如下所示:

public class Report
{
    public int Id {get; set;}
    public DateTime ActivityDate { get; set; }

    //Here is the date formation property
    public string FormattedDate => ActivityDate.ToString();
}

这里是被 jQuery 数据表调用的动作方法:

[JQDataTable]
public ActionResult Search()
{
     IQueryable<Report> data = db.Reports;
     return View("Index",data);
}

问题是,我无法获取格式化日期,而是收到以下错误:

The specified type member 'FormattedDate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我尝试并搜索了很多,但无法找到解决方案。在下一步中,我想将此日期转换为 PersianCalendar 对象并返回其字符串。

【问题讨论】:

  • 通常认为使用视图模型仅表示视图需要的数据的任何方式都是很好的做法。这将解决您的问题,因为您将查询原始报告,然后您的 reportviewmodel 将具有FormattedDate。在从原始模型转换为视图模型时,linq 到实体将不再是一个因素。

标签: json asp.net-mvc entity-framework linq model


【解决方案1】:

我在 Linq 查询中使用 ToString 时遇到过类似的问题。对于您的情况,我认为在视图中处理日期时间的转换并将日期时间变量保持原样会更容易。而是接受搜索操作的特定格式,解析收到的日期并进行查询。

在忍受了很长时间之后,我现在倾向于接受视图中的日期时间作为我明确指定格式的字符串(“yyyy-mm-dd”只是我个人的选择:P)并使用 DateTime.TryParseExact() 处理空输入也是如此。

希望对您有所帮助。编码愉快。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-14
    • 2014-07-27
    • 1970-01-01
    • 1970-01-01
    • 2013-11-28
    • 2017-05-31
    • 1970-01-01
    • 2015-12-02
    相关资源
    最近更新 更多