首页 > 解决方案 > 如何在 .NET Core 的实体框架中的原始 SQL 中添加 CAST

问题描述

我有一个用 .NET Core 编写的 Web 应用程序,我有一个接收参数并对数据库进行查询的 post 方法。

public IActionResult OnPostGetRegestrationList(string objId)
{       
    List<Flight> data = _context.Flight.FromSqlRaw("select id, side, reg, CAST(Actual_Date as date)as ActDate , CAST(Actual_Time as time)as ActTime from Flight where REG = {0} order by reg, ActDate, ActTime", objId).ToList();
    return new JsonResult(data);
}

如果没有演员表,查询将起作用,但我必须演员表,所以我可以得到这种格式的时间 '12:49:00.0000000' 而不是这种格式 '12/31/1899 12:49:00 PM' 完全错误,因为日期是自动生成的并且会出错。

如何CAST在实体框架中添加原始 SQL,并将其添加到订单中会产生相同的结果(将 CAST 添加到订单中有效)?这是一个有效的查询,但这不是我想要的。

 List<Flight> data = _context.Flight.FromSqlRaw("select id, side, reg, Actual_Date , Actual_Time from Flight where REG = {0} order by reg, CAST(Actual_Date as date), CAST(Actual_Time as time)", objId).ToList();

这是飞行类

public class Flight
{
   [Key]
    public Int64 id { get; set; }
    public string REG { get; set; }
    public string Side { get; set; }
    public string Actual_Date { get; set; }
    public string Actual_Time { get; set; }
  
}

数据库中的类

CREATE TABLE [dbo].[Flight](
[id] [bigint] IDENTITY(1,1) NOT NULL,
[REG] [nvarchar](max) NULL,
[Side] [nvarchar](max) NULL,
[Actual_Date] [nvarchar](max) NULL,
[Actual_Time] [nvarchar](max) NULL,
CONSTRAINT [PK_Flight] PRIMARY KEY CLUSTERED 
(
    [id] ASC
)

标签: sqlsql-serverentity-framework-coreef-core-3.1

解决方案


推荐阅读