实体框架6 SqlFunctions DateDiff未在nuget包中实现

Fra*_*k M 3 .net c# linq entity entity-framework

我刚刚将实体框架6(EntityFramework.dll版本6.0.0.0运行时版本v4.0.30319和EntityFramework.SqlServer版本6.0.0.0运行时版本v4.0.30319)的nuget包下载到我的4.5 Framework解决方案(它在多个项目中)

在其中一个项目中,我都引用并尝试实现DateDiffSql函数

RepositoryFactory.CreateReadOnly<MyEnity>()
 .Where(at => at.AccessedDate.HasValue 
              && at.CreatedDate >= startDate && at.CreatedDate <= endDate
              && System.Data.Entity.SqlServer.SqlFunctions.DateDiff("ss", at.CreatedDate, at.AccessedDate.Value) > 0)
 .GroupBy(at => at.Participant.Id)
 .Select(at => new TimeOnSite
     {
         TimeSpentInSeconds = at.Sum(p => p.AccessedDate.Value.Subtract(p.CreatedDate).TotalSeconds), 
         ParticipantId = at.Key
     }).ToList();
Run Code Online (Sandbox Code Playgroud)

令我惊讶的是,我在运行代码时收到了一个不受支持的异常.当我查看源代码时System.Data.Entity.SqlServer.SqlFunctions,所有DateDiff函数都没有实现,它们只抛出NotSupportedExceptions.一个例子如下:

    /// <summary>
/// Returns the count of the specified datepart boundaries crossed between the specified start date and end date.
/// </summary>
/// 
/// <returns>
/// The number of time intervals between the two dates.
/// </returns>
/// <param name="datePartArg">The part of the date to calculate the differing number of time intervals.</param><param name="startDate">The first date.</param><param name="endDate">The second date.</param>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "datePartArg")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "endDate")]
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "startDate")]
[DbFunction("SqlServer", "DATEDIFF")]
public static int? DateDiff(string datePartArg, DateTime? startDate, DateTime? endDate)
{
  throw new NotSupportedException(Strings.ELinq_DbFunctionDirectCall);
}
Run Code Online (Sandbox Code Playgroud)

我也尝试使用System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond已实现的,但得到以下异常:

LINQ to Entities无法识别方法'Int32 DateDiffSecond(System.DateTime,System.DateTime)'方法,并且此方法无法转换为商店表达式.

Fra*_*k M 17

我在找错了地方.正确的函数在System.Data.Entity.SqlServer.SqlFunctions中.结果证明是正确的

RepositoryFactory.CreateReadOnly<MyEntity>()
    .Where(at => at.AccessedDate.HasValue 
        && at.CreatedDate >= startDate && at.CreatedDate <= endDate
        && SqlFunctions.DateDiff("ss", at.CreatedDate, at.AccessedDate.Value) > 0)
    .GroupBy(at => at.Participant.Id)
    .Select(at => new TimeOnSite {
        TimeSpentInSeconds = at.Sum(p => 
            SqlFunctions.DateDiff("ss", p.CreatedDate, p.AccessedDate.Value)
        ),
        // p.AccessedDate.Value.Subtract(p.CreatedDate).TotalSeconds), 
        ParticipantId = at.Key
    })
    .ToList();
Run Code Online (Sandbox Code Playgroud)