gpt4 book ai didi

c# - 在 Dynamic LINQ to Entities 中使用 DateTime

转载 作者:太空狗 更新时间:2023-10-29 20:01:57 24 4
gpt4 key购买 nike

我正在使用 LINQ to Entities 检索商品购买日期,如下所示:

where EntityFunctions.TruncateTime(order.PurchaseDate) == myPurchaseDate.date

此处的关键是 DB 列包含日期和时间,因此必须去除时间以进行比较。此代码工作正常。

现在,我想使用动态 LINQ to Entities 做同样的事情。我正在使用 VS2010 代码示例文件夹中的 dynamic.cs。当我编码时:

.where("EntityFunctions.TruncateTime(PurchaseDate) == @0", myPurchaseDate.date);

或相同的任何变体我收到一条错误消息。我必须将什么编码为字符串值才能使其正常工作? (因为我可以在字符串中使用 .StartsWith 或 .Contains,所以我希望动态 LINQ 可以识别一些日期函数)。

我知道我可以将动态 LINQ 查询创建为一个日期范围,概念上:

PurchaseDate >= myPurchaseDate@midnight and PurchaseDate <= myPurchaseDate+23:59:59

事实上,从 SQL Server 的角度来看,日期范围可能更有效,但我想知道 Dynamic LINQ to Entities 中是否存在类似 TruncateTime 或 ToShortDate 的内容。

最佳答案

我最近开始在一个项目中使用动态 linq,并且还想比较没有时间组件的日期。 Microsoft 的动态 linq C# 示例代码 (Dynamic.cs) 支持一组固定的类型,EntityFunctions 不是其中之一。

但是通过一些实验,我发现只需将 EntityFunctions 添加到预定义类型的数组中就可以使用 TruncateTime 和可能的其他 EntityFunctions 还有方法。

这是 Dynamic.cs predefinedTypes 数组在我的项目中的样子:

static readonly Type[] predefinedTypes = {
typeof(Object),
typeof(Boolean),
typeof(Char),
typeof(String),
typeof(SByte),
typeof(Byte),
typeof(Int16),
typeof(UInt16),
typeof(Int32),
typeof(UInt32),
typeof(Int64),
typeof(UInt64),
typeof(Single),
typeof(Double),
typeof(Decimal),
typeof(DateTime),
typeof(TimeSpan),
typeof(Guid),
typeof(Math),
typeof(Convert),
typeof(System.Data.Objects.EntityFunctions) // JimM
};

使用这个修改后的 Dynamic.cs 文件,我能够创建动态 linq 查询,包括您问题中的 PurchaseDate 示例等表达式。

关于c# - 在 Dynamic LINQ to Entities 中使用 DateTime,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4949892/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com