我正在使用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),或者它无法识别类
这怎么办?
一些错误消息
类型'viwAttendancePre'中不存在适用的方法'DateDiff'
'viwAttendancePre'类型不存在属性或字段'Microsoft'
'viwAttendancePre'类型不存在属性或字段'Month'
LINQ to Entities无法识别方法'System.Nullable1[System.DateTime] CreateDateTime(System.Nullable
1 [System.Int32],System.Nullable1[System.Int32], System.Nullable
1 [System.Int32],System.Nullable1[System.Int32], System.Nullable
1 [System .Int32],System.Nullable`1 [System.Double])方法,并且该方法不能转换为商店表达式。
类型'EntityFunctions'中不存在适用的方法'CreateDateTime'
类型'viwAttendancePre'中不存在属性或字段'DbFunctions'
LINQ to Entities仅支持无参数构造函数和初始化程序。
'viwAttendancePre'类型中不存在适用的方法'Date'
环境
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.'"
答案 0 :(得分:2)
应该可以使用System.Linq.Dynamic.Core。
void Main()
{
var r = Reservations.Select("DateTime(CheckinDate.Year,1,1)");
r.Dump();
}
对于Entity Framework 6,您需要使用:
var datesDynamic = ctx.Reservations.Select("DbFunctions.CreateDateTime(CheckinDate.Year, 1, 1, 0, 0, 0)");
请注意,您需要为CreateDateTime
方法提供所有参数。