如何获得 month/year 等的第一天?

How to get first day of month/year etc?

我正在使用 Linq.Dynamic 查询 SQL Server 数据库。

我有一个名为 'EnteredOn' 的日期字段,我需要将其转换为该月(或年、分钟等)的第一秒

我基本上尝试了所有方法,但所有方法都会引发错误

这是我的一些尝试

Return $"DateTime({FieldName}.Year,1,1)"
Return $"DateTime({FieldName}.Year,{FieldName}.Month,1)"
Return $"DateTime({FieldName}.Year,{FieldName}.Month,{FieldName}.Day)"
Return $"DateAndTime.DateDiff(2, 0, {FieldName})"
Return $"EntityFunctions.CreateDateTime({FieldName}.Year,{FieldName}.Month,{FieldName}.Day,0,0,0)"
Return $"DbFunctions.CreateDateTime({FieldName}.Year,{FieldName}.Month,{FieldName}.Day,0,0,0)"

要么我得到一个错误,我只能使用无参数构造函数(所以前 3 个不工作),或者不存在这样的 属性 或字段(DateDiff),或者它不识别 Class

如何做到这一点?

一些错误信息

No applicable method 'DateDiff' exists in type 'viwAttendancePre'
No property or field 'Microsoft' exists in type 'viwAttendancePre'
No property or field 'Month' exists in type 'viwAttendancePre'
LINQ to Entities does not recognize the method 'System.Nullable1[System.DateTime] CreateDateTime(System.Nullable1[System.Int32], System.Nullable1[System.Int32], System.Nullable1[System.Int32], System.Nullable1[System.Int32], System.Nullable1[System.Int32], System.Nullable`1[System.Double])' method, and this method cannot be translated into a store expression.
No applicable method 'CreateDateTime' exists in type 'EntityFunctions'
No property or field 'DbFunctions' exists in type 'viwAttendancePre'
Only parameterless constructors and initializers are supported in LINQ to Entities.
No applicable method 'Date' exists in type 'viwAttendancePre'

环境

Linq 包

 <Reference Include="System.Linq.Dynamic, Version=1.0.6132.35681, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\..\_packages\System.Linq.Dynamic.1.0.7\lib\net40\System.Linq.Dynamic.dll</HintPath>
<Private>True</Private>
</Reference>

更新 - 使用System.Linq.Dynamic.Core

我知道如果我不使用查询中的字段,它会按如下方式工作

Dim d = GetSystemContext()
Dim goodq = d.Set(GetType(Attendance)).AsQueryable.Select("new (DateTime(2000,1,1) as mydate)")' this returns just fine
Dim badq = d.Set(GetType(Attendance)).AsQueryable.Select("new (DateTime(AddedOn.Year,1,1) as mydate)")' this throws "System.NotSupportedException: 'Only parameterless constructors and initializers are supported in LINQ to Entities.'"

应该可以使用 System.Linq.Dynamic.Core

EFCore

void Main()
{
    var r = Reservations.Select("DateTime(CheckinDate.Year,1,1)");
    r.Dump();
}

EFCore 结果

EFCore 已生成 SQL

EF 6

对于Entity Framework6,你需要使用:

var datesDynamic = ctx.Reservations.Select("DbFunctions.CreateDateTime(CheckinDate.Year, 1, 1, 0, 0, 0)");

请注意,您需要向 CreateDateTime 方法提供所有参数。