Skip to content

GroupBy on a Date results in an exception #2296

Closed

Description

@stuartag

When using a GroupBy on a DateTime field that is holding a date, the output formatter raises an exception:

Microsoft.OData.ODataException: An ODataPrimitiveValue was instantiated with a value of type 'System.DateTime'. ODataPrimitiveValue can only wrap values which can be represented as primitive EDM types.
   at Microsoft.OData.ODataPrimitiveValue..ctor(Object value)
   at Microsoft.OData.ODataValueUtils.ToODataValue(Object objectToConvert)
   at Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.CreateODataPropertiesFromDynamicType(EdmEntityType entityType, Object graph, Dictionary`2 dynamicTypeProperties)

This is despite the underlying EdmModel defining the field as a Date

This is in Microsoft.AspNet.OData.Shared v7.4.1

Expected result

The result of the grouping would be interpreted correctly as a Date and outputted correctly.

Actual result

The formatter throws an ODataException

Additional detail

The issue appears to be where fields from the EdmModel are added to a dynamic type. They lose their EdmModel type and are only held as CLR types. When the formatter calls CreateODataPropertiesFromDynamicType, the value is not converted to a Edm.Date type. I have managed to work around this by altering this method to check the original type from the EdmEntityType parameter's properties and perform the necessary conversion to Date, DateTimeOffset or TimeOfDay.

Activity

  1. ElizabethOkerio commented on Jul 14, 2020

    @ElizabethOkerio
    Contributor

    @stuartag can you share a repro for the issue. We have a date built in function to convert datetime and datetimeoffset value. Can you try it and let us know the result. Here is the link http://docs.oasis-open.org/odata/odata/v4.01/odata-v4.01-part2-url-conventions.html#_Toc31360997

  2. stuartag commented on Jul 14, 2020

    @stuartag
    Author

    EDIT: This isn't the same error as above - See next example

    Sure. Here's an example

    using Microsoft.AspNet.OData;
    using Microsoft.AspNet.OData.Builder;
    using Microsoft.AspNet.OData.Extensions;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.OData.Edm;
    using System;
    using System.Linq;
    
    namespace ODataTest
    {
        public static class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebHost.CreateDefaultBuilder()
                    .ConfigureServices(services => {
                        services.AddControllers();
                        services.AddOData();
                    })
                    .Configure(app =>
                    {
                        app.UseRouting();
                        app.UseEndpoints(endpoints =>
                        {
                            endpoints.MapControllers();
                            endpoints.EnableDependencyInjection();
                            endpoints.MapODataRoute("odata", "odata", GetEdmModel());
                            endpoints.Select().Filter().OrderBy().Count().MaxTop(200).SkipToken().Expand();
                        });
                    });
                var testServer = new TestServer(builder);
    
                var client = testServer.CreateClient();
    
                var uri = "/odata/Test?$apply=groupby((Date), aggregate($count as Cnt))";
    
                var response = client.GetAsync(uri).Result;
                Console.Write(response.Content.ReadAsStringAsync().Result);
            }
    
            private static IEdmModel GetEdmModel()
            {
                ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
                builder.EntitySet<Book>("Books")
                    .EntityType.Property(x => x.Date).AsDate();
                return builder.GetEdmModel();
            }
        }
    
        [ApiController]
        [Route("odata/[controller]")]
        public class TestController : ControllerBase
        {
            private readonly IQueryable<Book> books;
            public TestController()
            {
                this.books = new[]
                {
                    new Book{ID = 1, Title = "ABC", Date = new DateTime(2020,5,1)},
                    new Book{ID = 2, Title = "DEF", Date = new DateTime(2020,6,1)},
                    new Book{ID = 3, Title = "GHI", Date = new DateTime(2020,4,1)},
                    new Book{ID = 4, Title = "JKL", Date = new DateTime(2020,5,1)},
                    new Book{ID = 5, Title = "MNO", Date = new DateTime(2020,5,1)},
                }.AsQueryable();
            }
    
            [EnableQuery]
            public IQueryable<Book> Get()
            {
                return books;
            }
        }
    
        public class Book
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public DateTime Date { get; set; }
        }
    }

    This fails with the following exception:

    System.AggregateException
    HResult=0x80131500
    Message=One or more errors occurred. (Unable to cast object of type 'System.DateTime' to type 'Microsoft.AspNet.OData.Query.Expressions.GroupByWrapper'.)
    Source=System.Private.CoreLib
    StackTrace:
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
    at ConsoleApp4.Program.Main(String[] args) in ...\Program.cs:line 42

    Inner Exception 1:
    InvalidCastException: Unable to cast object of type 'System.DateTime' to type 'Microsoft.AspNet.OData.Query.Expressions.GroupByWrapper'.

  3. stuartag commented on Jul 14, 2020

    @stuartag
    Author

    Apologies. That's a different exception as it was going down a non-OData route. This is producing the original exception:

    using Microsoft.AspNet.OData;
    using Microsoft.AspNet.OData.Builder;
    using Microsoft.AspNet.OData.Extensions;
    using Microsoft.AspNetCore;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.TestHost;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.OData.Edm;
    using System;
    using System.Linq;
    using System.Net.Http;
    using System.Net.Http.Headers;
    
    namespace ConsoleApp4
    {
        public static class Program
        {
            public static void Main(string[] args)
            {
                var builder = WebHost.CreateDefaultBuilder()
                    .ConfigureServices(services => {
                        services.AddControllers();
                        services.AddOData();
                    })
                    .Configure(app =>
                    {
                        app.UseRouting();
                        app.UseEndpoints(endpoints =>
                        {
                            endpoints.MapODataRoute("odata", "odata", GetEdmModel());
                            endpoints.MapControllers();
                            endpoints.Select().Filter().OrderBy().Count().MaxTop(200).SkipToken().Expand();
                        });
                    });
                var testServer = new TestServer(builder);
    
                var client = testServer.CreateClient();
    
                var uri = "/odata/Books?$apply=groupby((Date), aggregate($count as Cnt))";
                var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost" + uri);
                request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));
                var response = client.SendAsync(request).Result;
                Console.Write(response.Content.ReadAsStringAsync().Result);
            }
    
            private static IEdmModel GetEdmModel()
            {
                ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
                var booksType = builder.EntitySet<Book>("Books").EntityType;
                booksType.HasKey(x => x.ID);
                booksType.Property(x => x.Date).AsDate();
                return builder.GetEdmModel();
            }
        }
    
        [ApiController]
        [Route("odata/[controller]")]
        public class Books : ControllerBase
        {
            private readonly IQueryable<Book> books;
            public Books()
            {
                this.books = new[]
                {
                    new Book{ID = 1, Title = "ABC", Date = new DateTime(2020,5,1)},
                    new Book{ID = 2, Title = "DEF", Date = new DateTime(2020,6,1)},
                    new Book{ID = 3, Title = "GHI", Date = new DateTime(2020,4,1)},
                    new Book{ID = 4, Title = "JKL", Date = new DateTime(2020,5,1)},
                    new Book{ID = 5, Title = "MNO", Date = new DateTime(2020,5,1)},
                }.AsQueryable();
            }
    
            [HttpGet]
            [EnableQuery(PageSize = 200)]
            public IQueryable<Book> Get()
            {
                return books;
            }
        }
    
        public class Book
        {
            public int ID { get; set; }
            public string Title { get; set; }
            public DateTime Date { get; set; }
        }
    }

    System.AggregateException
    HResult=0x80131500
    Message=One or more errors occurred. (Error while copying content to a stream.)
    Source=System.Private.CoreLib
    StackTrace:
    at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
    at System.Threading.Tasks.Task1.GetResultCore(Boolean waitCompletionNotification) at System.Threading.Tasks.Task1.get_Result()
    at ConsoleApp4.Program.Main(String[] args) in ...\Program.cs:line 44

    This exception was originally thrown at this call stack:
    Microsoft.OData.ODataPrimitiveValue.ODataPrimitiveValue(object)
    Microsoft.OData.ODataValueUtils.ToODataValue(object)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.CreateODataPropertiesFromDynamicType(Microsoft.OData.Edm.EdmEntityType, object, System.Collections.Generic.Dictionary<Microsoft.OData.Edm.IEdmProperty, object>)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.WriteDynamicTypeResource(object, Microsoft.OData.ODataWriter, Microsoft.OData.Edm.IEdmTypeReference, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.WriteResource(object, Microsoft.OData.ODataWriter, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext, Microsoft.OData.Edm.IEdmTypeReference)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSerializer.WriteObjectInline(object, Microsoft.OData.Edm.IEdmTypeReference, Microsoft.OData.ODataWriter, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteResourceSet(System.Collections.IEnumerable, Microsoft.OData.Edm.IEdmTypeReference, Microsoft.OData.ODataWriter, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteObjectInline(object, Microsoft.OData.Edm.IEdmTypeReference, Microsoft.OData.ODataWriter, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext)
    Microsoft.AspNet.OData.Formatter.Serialization.ODataResourceSetSerializer.WriteObject(object, System.Type, Microsoft.OData.ODataMessageWriter, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext)
    Microsoft.AspNet.OData.Formatter.ODataOutputFormatterHelper.WriteToStream(System.Type, object, Microsoft.OData.Edm.IEdmModel, Microsoft.OData.ODataVersion, System.Uri, System.Net.Http.Headers.MediaTypeHeaderValue, Microsoft.AspNet.OData.Interfaces.IWebApiUrlHelper, Microsoft.AspNet.OData.Interfaces.IWebApiRequestMessage, Microsoft.AspNet.OData.Interfaces.IWebApiHeaders, System.Func<System.IServiceProvider, Microsoft.AspNet.OData.Formatter.ODataMessageWrapper>, System.Func<Microsoft.OData.Edm.IEdmTypeReference, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializer>, System.Func<System.Type, Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializer>, System.Func<Microsoft.AspNet.OData.Formatter.Serialization.ODataSerializerContext>)
    ...
    [Call Stack Truncated]

    Inner Exception 1:
    HttpRequestException: Error while copying content to a stream.

    Inner Exception 2:
    IOException:

    Inner Exception 3:
    ODataException: An ODataPrimitiveValue was instantiated with a value of type 'System.DateTime'. ODataPrimitiveValue can only wrap values which can be represented as primitive EDM types.

  4. SireGoatMonkey commented on Aug 13, 2020

    @SireGoatMonkey

    I believe this is the same as: #912

  5. ElizabethOkerio commented on Sep 3, 2020

    @ElizabethOkerio
    Contributor
  6. SireGoatMonkey commented on Sep 3, 2020

    @SireGoatMonkey

    @ElizabethOkerio
    Are you suggesting we don't use DateTime for any of our properties? We should only use DateTimeOffset?

    This won't work for my scenario as my properties represents a Date and are tagged with the following attribute:
    [Column(TypeName = "date")]

    If I try to attribute a DateTimeOffset like that, it results in an error when I call GetEdmModel:
    'The property 'ContractDate' on type 'Contracts.Contract' must be a System.DateTime property.
    Parameter name: property'

  7. ElizabethOkerio commented on Sep 3, 2020

    @ElizabethOkerio
    Contributor

    @SireGoatMonkey if you decide to use DateTimeOffset then you need to get rid of this line booksType.Property(x => x.Date).AsDate() from your model builder..

    Basically the whole point is. OData does not have a built-in primitive type for DateTime . So what happens is System.DateTime is translated to Edm.DateTimeOffset by default.

    If you use booksType.Property(x => x.Date).AsDate() in your model builder then System.DateTime gets translated to Edm.Date and should work okay without any issue. We are looking into this though to ensure it works as expected.

    https://docs.microsoft.com/en-us/odata/webapi/date-timeofday-with-entity-framework

  8. stuartag commented on Sep 3, 2020

    @stuartag
    Author

    I think that's my point. I want to use Edm.Date, however C# does not have a 'date' type. In my second example above, I have used .AsDate() in the model builder and it isn't working correctly within the ODataResourceSerializer.

    I have a workaround I'm using in a custom version of this class. Instead of blindly setting the new ODataProperty.Value to the dynamicObject's prop.Value, I check whether prop.Value is a DateTime and if so, check what type the EdmEntityType is expecting and construct a new Date or a new DateTimeOffset from the DateTime accordingly.

  9. ElizabethOkerio commented on Sep 3, 2020

    @ElizabethOkerio
    Contributor

    @stuartag OData has a Date struct, Microsoft.OData.Edm.Date whose primitive value is Edm.Date that you can use.

  10. SireGoatMonkey commented on Sep 3, 2020

    @SireGoatMonkey

    Microsoft.OData.Edm.Date doesn't play well with Entity Framework when using that property in a filter. You'll get the following error:
    "NotSupportedException: The specified type member 'ContractDate' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported."

    Edit:
    @ElizabethOkerio
    This is actually pointed out in the link you shared:
    https://docs.microsoft.com/en-us/odata/webapi/date-timeofday-with-entity-framework

    The resolutions is to use a DateTime and either attribute it with [Column(TypeName = "date")], or to use the AsDate() extension method. Both of these solutions require the use of DateTime. And that is the problem. As the DateTime cannot be converted to and OData type. As pointed out in Issue #1945.

    P.S. Thank you for the responses the last couple days! It's great to see some movement on this.

  11. ElizabethOkerio commented on Sep 7, 2020

    @ElizabethOkerio
    Contributor
  12. linked a pull request that will close this issuegroup by on date throws exceptions #2302on Oct 7, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions