我遵循这里的建议:
What is the correct SQL type to store a .Net Timespan with values > 24:00:00?
在名为TimesheetEntry的模型中,我有:
public Int64 NetLengthTicks { get; set; }
[NotMapped]
public TimeSpan NetLength
{
get { return TimeSpan.FromTicks(NetLengthTicks); }
set { NetLengthTicks = value.Ticks; }
}
我试图这样做:
var shiftsData = from shift in filteredShifts
where shift.IsDeleted == false
select new
{
shift.TimesheetShiftId,
shift.UserId,
shift.HasShiftEnded,
shift.StartTime,
shift.EndTime,
Entries = from entry in shift.Entries
where entry.IsDeleted == false
select new
{
entry.TimesheetEntryId,
entry.TimesheetShiftId,
entry.EntryType,
entry.StartTimeSpan,
entry.NetLength,
}
};
我得到例外:
The specified type member 'NetLength' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.
我尝试将投影更改为:
NetLength = TimeSpan.FromTicks(entry.NetLengthTicks)
但是这给了例外:
LINQ to Entities does not recognize the method 'System.TimeSpan FromTicks(Int64)' method, and this method cannot be translated into a store expression.
然后我尝试创建一个表达式来进行转换:
public static Expression<Func<DAL.Models.TimesheetEntry, TimeSpan>> NetLengthExpression
{
get
{
return e => TimeSpan.FromTicks(e.NetLengthTicks);
}
}
// in the projection
NetLength = NetLengthExpression
但那扔了:
The LINQ expression node type 'Lambda' is not supported in LINQ to Entities.
有没有办法将NetLength公开为我的查询中返回的TimeSpan?
答案 0 :(得分:1)
除非EF知道如何进行转换,否则您无法在数据库端进行转换,而且听起来EF并不知道如何进行转换。
您必须使用辅助方法进行转换。
我通常在我的DataContext
类上使用帮助器方法来处理这种情况,因为如果我正在进行查询,那么我通常会使用该类的实例。
public class DataContext : DbContext {
public TimeSpan GetTimeSpan(Int64 ticks) {
return TimeSpan.FromTicks(ticks);
}
// ... other code
}
修改强>
这也可能是一个选项:
var shiftsData = from shift in filteredShifts
where shift.IsDeleted == false
select new
{
shift.TimesheetShiftId,
shift.UserId,
shift.HasShiftEnded,
shift.StartTime,
shift.EndTime,
Entries = from entry in shift.Entries
where entry.IsDeleted == false
select entry
};
如果您删除了查询创建的匿名类,而只是select entry
,那么您将获得Entry
类的实例,该类将填充您的NetLengthTicks
属性并让你使用你的NetLength
吸气剂。但请注意,如果您投影该类的实例,则可能会选择比实际需要的更多的行。