Entity framework core 与EF core中的DateTime相比,生成的日期字符串以毫秒为单位为6位小数
我正在做这个查询Entity framework core 与EF core中的DateTime相比,生成的日期字符串以毫秒为单位为6位小数,entity-framework-core,ef-core-3.1,Entity Framework Core,Ef Core 3.1,我正在做这个查询 var sourceItems = await this.dbContext.Orders .AsNoTracking() .Where(item => item.OrderDate > new DateTime(2019, 1, 1)) .Select(order => new { order.CustomerCode }) .ToListAsync(); 我得到了这个sql查询 SELECT [o].[CustomerCode] FROM [Or
var sourceItems = await this.dbContext.Orders
.AsNoTracking()
.Where(item => item.OrderDate > new DateTime(2019, 1, 1))
.Select(order => new
{
order.CustomerCode
})
.ToListAsync();
我得到了这个sql查询
SELECT [o].[CustomerCode]
FROM [Order] AS [o]
WHERE [o].[OrderDate] > '2019-01-01T00:00:00.0000000'
这是失败的
核心Microsoft SqlClient数据提供程序:从字符串转换日期和/或时间时,转换失败
我使用的是EF Core 3.1.5
如果我直接运行sql查询,如果我将日期毫秒部分的数字从6个零减少到3个零或更少,它就会工作
如何让EF Core甚至跳过日期的毫秒部分?EF Core从其他操作数推断常量值的提供程序类型。在这种情况下,从
item.OrderDate
文本的格式表示EF Core采用datetime2
提供程序类型(DateTime
CLR类型的默认映射),而异常表示实际列类型为DateTime
要解决此问题,您必须让EF Core知道实际的类型,例如,将以下内容添加到您的OnModelCreating
override中:
modelBuilder.Entity()
.Property(e=>e.OrderDate)
.HasColumnType(“日期时间”);
现在,查询将使用正确的'2019-01-01T00:00:00.000'
文本
另一个改进是消除literal并让EF Core绑定参数。这是通过将new DateTime(…)
表达式放入查询表达式树外部的变量中,并在内部使用该变量来实现的:
var afterDate=新的日期时间(2019,1,1);//item.OrderDate>afterDate)//新建
{
order.CustomerCode
})
.ToListAsync();