首页 > 代码库 > 谨慎DateTime.Now在EF的query中的使用

谨慎DateTime.Now在EF的query中的使用

执行如下代码:

var query = from tr in _carrierRepository
select new BaseCarrier
{
CarrierCode = tr.CarrierCode,
CarrierName = tr.CName,
Alias = tr.Alias,
Country = tr.Country,
CreateTime = DateTime.Now
};

var list = query.ToList();

 

通过SqlServer的Profiler可以看出来,生成的sql是:

SELECT
1 AS [C1],
[Extent1].[CarrierCode] AS [CarrierCode],
[Extent1].[CName] AS [CName],
[Extent1].[Alias] AS [Alias],
[Extent1].[Country] AS [Country],
CAST( SysDateTime() AS datetime2) AS [C2]
FROM [dbo].[T_Code_Carriers] AS [Extent1]

即DateTime.Now转换成了使用 SysDateTime()这个函数了,这与我们的通过DateTime.Now获取应用服务器的系统时间的期望并不一致。

谨慎DateTime.Now在EF的query中的使用