You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
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.
EDIT: This isn't the same error as above - See next example
Sure. Here's an example
usingMicrosoft.AspNet.OData;usingMicrosoft.AspNet.OData.Builder;usingMicrosoft.AspNet.OData.Extensions;usingMicrosoft.AspNetCore;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.TestHost;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.OData.Edm;usingSystem;usingSystem.Linq;namespaceODataTest{publicstaticclassProgram{publicstaticvoidMain(string[]args){varbuilder=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();});});vartestServer=newTestServer(builder);varclient=testServer.CreateClient();varuri="/odata/Test?$apply=groupby((Date), aggregate($count as Cnt))";varresponse=client.GetAsync(uri).Result;Console.Write(response.Content.ReadAsStringAsync().Result);}privatestaticIEdmModelGetEdmModel(){ODataConventionModelBuilderbuilder=newODataConventionModelBuilder();builder.EntitySet<Book>("Books").EntityType.Property(x =>x.Date).AsDate();returnbuilder.GetEdmModel();}}[ApiController][Route("odata/[controller]")]publicclassTestController:ControllerBase{privatereadonlyIQueryable<Book>books;publicTestController(){this.books=new[]{newBook{ID=1,Title="ABC",Date=newDateTime(2020,5,1)},newBook{ID=2,Title="DEF",Date=newDateTime(2020,6,1)},newBook{ID=3,Title="GHI",Date=newDateTime(2020,4,1)},newBook{ID=4,Title="JKL",Date=newDateTime(2020,5,1)},newBook{ID=5,Title="MNO",Date=newDateTime(2020,5,1)},}.AsQueryable();}[EnableQuery]publicIQueryable<Book>Get(){returnbooks;}}publicclassBook{publicintID{get;set;}publicstringTitle{get;set;}publicDateTimeDate{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'.
Apologies. That's a different exception as it was going down a non-OData route. This is producing the original exception:
usingMicrosoft.AspNet.OData;usingMicrosoft.AspNet.OData.Builder;usingMicrosoft.AspNet.OData.Extensions;usingMicrosoft.AspNetCore;usingMicrosoft.AspNetCore.Builder;usingMicrosoft.AspNetCore.Hosting;usingMicrosoft.AspNetCore.Mvc;usingMicrosoft.AspNetCore.TestHost;usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.OData.Edm;usingSystem;usingSystem.Linq;usingSystem.Net.Http;usingSystem.Net.Http.Headers;namespaceConsoleApp4{publicstaticclassProgram{publicstaticvoidMain(string[]args){varbuilder=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();});});vartestServer=newTestServer(builder);varclient=testServer.CreateClient();varuri="/odata/Books?$apply=groupby((Date), aggregate($count as Cnt))";varrequest=newHttpRequestMessage(HttpMethod.Get,"http://localhost"+uri);request.Headers.Accept.Add(MediaTypeWithQualityHeaderValue.Parse("application/json"));varresponse=client.SendAsync(request).Result;Console.Write(response.Content.ReadAsStringAsync().Result);}privatestaticIEdmModelGetEdmModel(){ODataConventionModelBuilderbuilder=newODataConventionModelBuilder();varbooksType=builder.EntitySet<Book>("Books").EntityType;booksType.HasKey(x =>x.ID);booksType.Property(x =>x.Date).AsDate();returnbuilder.GetEdmModel();}}[ApiController][Route("odata/[controller]")]publicclassBooks:ControllerBase{privatereadonlyIQueryable<Book>books;publicBooks(){this.books=new[]{newBook{ID=1,Title="ABC",Date=newDateTime(2020,5,1)},newBook{ID=2,Title="DEF",Date=newDateTime(2020,6,1)},newBook{ID=3,Title="GHI",Date=newDateTime(2020,4,1)},newBook{ID=4,Title="JKL",Date=newDateTime(2020,5,1)},newBook{ID=5,Title="MNO",Date=newDateTime(2020,5,1)},}.AsQueryable();}[HttpGet][EnableQuery(PageSize=200)]publicIQueryable<Book>Get(){returnbooks;}}publicclassBook{publicintID{get;set;}publicstringTitle{get;set;}publicDateTimeDate{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
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.
@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'
@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.
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.
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."
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.
Activity
ElizabethOkerio commentedon Jul 14, 2020
@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
stuartag commentedon Jul 14, 2020
EDIT: This isn't the same error as above - See next example
Sure. Here's an example
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.Task
1.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'.
stuartag commentedon Jul 14, 2020
Apologies. That's a different exception as it was going down a non-OData route. This is producing the original exception:
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.Task
1.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.
SireGoatMonkey commentedon Aug 13, 2020
I believe this is the same as: #912
ElizabethOkerio commentedon Sep 3, 2020
#1945
SireGoatMonkey commentedon Sep 3, 2020
@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'
ElizabethOkerio commentedon Sep 3, 2020
@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 isSystem.DateTimeis translated toEdm.DateTimeOffsetby default.If you use
booksType.Property(x => x.Date).AsDate()in your model builder thenSystem.DateTimegets translated toEdm.Dateand 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
stuartag commentedon Sep 3, 2020
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.
ElizabethOkerio commentedon Sep 3, 2020
@stuartag OData has a Date struct,
Microsoft.OData.Edm.Datewhose primitive value isEdm.Datethat you can use.SireGoatMonkey commentedon Sep 3, 2020
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.
ElizabethOkerio commentedon Sep 7, 2020
@stuartag @SireGoatMonkey