You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Entity Framework 4.0 如何拼接日期与时间字段为指定格式DateTime

EF4.0 拼接Receipt表DATE与TIME字段实现方案

首先确认Receipt实体类属性映射正确,EF4.0原生支持SQL Server DATE类型映射为DateTime、TIME类型映射为TimeSpan:

public class Receipt
{
    public int id { get; set; }
    public int idcustom { get; set; }
    public int idstaff { get; set; }
    public DateTime Daypayat { get; set; }
    public TimeSpan Timepayat { get; set; }
    public int total { get; set; }
}

场景1:数据量较小,内存中拼接

直接查询数据加载到内存后拼接,写法最简单:

using (var context = new YourDbContext())
{
    // 先将数据加载到内存
    var receiptList = context.Receipt.ToList();
    // 拼接日期时间并格式化
    var formatResult = receiptList.Select(r => new 
    {
        ReceiptId = r.id,
        PayTime = r.Daypayat.Add(r.Timepayat).ToString("dd/MM/yyyy hh:mm")
    }).ToList();
}

场景2:需在数据库层面计算

如果需要在查询条件中使用拼接后的时间、或者减少不必要的字段传输,可以用EF4.0内置的EntityFunctions实现SQL层面的计算:

using System.Data.Objects; // 需引入该命名空间

using (var context = new YourDbContext())
{
    // 数据库层面计算完整时间
    var queryResult = context.Receipt.Select(r => new
    {
        r.id,
        FullPayTime = EntityFunctions.AddDateTime(r.Daypayat, 0, 0, 0, 
                                r.Timepayat.Hours, r.Timepayat.Minutes, 0)
    }).ToList();
    // 内存中格式化
    var formatResult = queryResult.Select(r => new 
    {
        ReceiptId = r.id,
        PayTime = r.FullPayTime.Value.ToString("dd/MM/yyyy hh:mm")
    }).ToList();
}

注意事项

  • 不要直接在IQueryable查询语句中执行ToString("dd/MM/yyyy hh:mm")操作,EF4.0无法将该方法转换为SQL语句,会抛出运行时异常,需待查询结果加载到内存后再做格式化。
  • 若需要24小时制的时间格式,将格式字符串中的hh替换为HH即可。

内容的提问来源于stack exchange,提问作者Levents

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 03:36:01