【发布时间】:2014-04-04 15:48:00
【问题描述】:
我刚刚将实体框架 6 的 nuget 包(EntityFramework.dll 版本 6.0.0.0 运行时版本 v4.0.30319 和 EntityFramework.SqlServer 版本 6.0.0.0 运行时版本 v4.0.30319)下载到我的 4.5 框架解决方案中(它在多个项目)
在我引用并尝试实现DateDiff Sql 函数的项目之一中
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();
令我惊讶的是,我在运行代码时收到了不受支持的异常。当我查看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);
}
我也尝试使用System.Data.Linq.SqlClient.SqlMethods.DateDiffSecond 实现,但得到以下异常:
LINQ to Entities 无法识别方法 'Int32 DateDiffSecond(System.DateTime, System.DateTime)' 方法,并且该方法无法转换为存储表达式。
【问题讨论】:
-
IMO 它是 LINQ2SQL 功能。
-
你的数据库是 Sql Server 吗?
标签: c# .net linq entity-framework entity