Using DateTime in Dynamic LINQ to Entities

前端 未结 4 994
醉梦人生
醉梦人生 2021-01-05 09:34

I am using LINQ to Entities to retrieve item purchase dates as follows:

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


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-05 09:51

    I recently started using dynamic linq for a project and also wanted to compare dates without the time component. Microsoft's dynamic linq C# sample code (Dynamic.cs) supports a fixed set of types, and EntityFunctions isn't one of them.

    But with a little experimentation, I found that just adding EntityFunctions to the array of predefined types enables the use of TruncateTime and likely other EntityFunctions methods too.

    Here's what the Dynamic.cs predefinedTypes array looks like in my project:

    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
    };
    

    With this modified Dynamic.cs file, I'm able to create dynamic linq queries including expressions like the PurchaseDate example in your question.

提交回复
热议问题