获取EF投影中的时间跨度属性,用于从刻度转换的时间跨度

本文关键字:时间跨度 转换 用于 属性 EF 投影 获取 | 更新日期: 2023-09-27 18:17:59

我遵循这里的建议:

什么是正确的SQL类型来存储值>24:00:00吗?

在一个名为TimesheetEntry的模型中,我有:

public Int64 NetLengthTicks { get; set; }
[NotMapped]
public TimeSpan NetLength
{
    get { return TimeSpan.FromTicks(NetLengthTicks); }
    set { NetLengthTicks = value.Ticks; }
}

I'm trying this:

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暴露为要在我的查询中返回的时间跨度?

获取EF投影中的时间跨度属性,用于从刻度转换的时间跨度

除非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 getter。但是请注意,如果您投影该类的一个实例,您可能会选择比实际需要更多的行。