Unable to return a single Entity from a collection bound function.
Adding a collection-bound function gives an error when it is defined to return a single entity. No problems occur when a primitive type, a complex type or a collection of entities is returned.
Assemblies affected
OData .Net lib 7.2
Reproduce steps
First define an entityset:
builder.EntitySet<MyEntity>("Entities");
Next define the collection-bound function:
builder.EntityType<MyEntity>().Collection
.Function("MyFunction")
.Returns<MyEntity>();
And implement the function on the controller:
[HttpGet]
public IHttpActionResult MyFunction()
{
return Ok(new MyEntity());
}
Expected result
The invoked function should return an HTTP OK response with the correct data.
Actual result
The following exception is thrown:
Exception thrown: 'Microsoft.OData.ODataException' in Microsoft.OData.Core.dll
When writing a JSON response, a user model must be specified and the entity set and entity
type must be passed to the ODataMessageWriter.CreateODataResourceWriter method or the
ODataResourceSerializationInfo must be set on the ODataResource or ODataResourceSet that
is being written.
Partial stacktrace:
Microsoft.OData.Core.dll!Microsoft.OData.ODataResourceTypeContext.ValidateAndReturn<string>(string value) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataResourceTypeContext.NavigationSourceName.get() Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataContextUrlInfo.Create(Microsoft.OData.ODataResourceTypeContext typeContext, bool isSingle, Microsoft.OData.ODataUri odataUri) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightResourceSerializer.WriteResourceContextUri.AnonymousMethod__0() Unknown
Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightSerializer.WriteContextUriProperty(Microsoft.OData.ODataPayloadKind payloadKind, System.Func<Microsoft.OData.ODataContextUrlInfo> contextUrlInfoGen, Microsoft.OData.ODataContextUrlInfo parentContextUrlInfo, string propertyName) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightResourceSerializer.WriteResourceContextUri(Microsoft.OData.ODataResourceTypeContext typeContext, Microsoft.OData.ODataContextUrlInfo parentContextUrlInfo) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightWriter.StartResource(Microsoft.OData.ODataResource resource) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStartResourceImplementation.AnonymousMethod__0() Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.InterceptException(System.Action action) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStartResourceImplementation(Microsoft.OData.ODataResource resource) Unknown
Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStart(Microsoft.OData.ODataResource resource) Unknown
System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteResource(object graph, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext, Microsoft.OData.Edm.IEdmTypeReference expectedType) Unknown
System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteObjectInline(object graph, Microsoft.OData.Edm.IEdmTypeReference expectedType, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Unknown
> ODataService.exe!RQuest.Web.OData.CustomODataResourceSerializer.WriteObjectInline(object graph, Microsoft.OData.Edm.IEdmTypeReference expectedType, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Line 78 C#
System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteObject(object graph, System.Type type, Microsoft.OData.ODataMessageWriter messageWriter, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Unknown
System.Web.OData.dll!System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.Http.Headers.HttpContentHeaders contentHeaders) Unknown
System.Web.OData.dll!System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken) Unknown
System.Net.Http.Formatting.dll!System.Net.Http.Formatting.MediaTypeFormatter.WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) Unknown
System.Net.Http.Formatting.dll!System.Net.Http.ObjectContent.SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) Unknown
System.Net.Http.dll!System.Net.Http.HttpContent.LoadIntoBufferAsync(long maxBufferSize) Unknown
System.Net.Http.dll!System.Net.Http.HttpContent.LoadIntoBufferAsync() Unknown
System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.BufferResponseContentAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken) Unknown
Additional details
When the function returns a primitive type, a complex type or a collection of entities then all works fine. For example, the following works:
[HttpGet]
public IHttpActionResult MyFunction()
{
return Ok(new MyEntity[] {MyEntity()});
}
change "Returns
On Thu, Jun 1, 2017 at 2:26 PM he-man71 [email protected] wrote:
Adding a collection-bound function gives an error when it is defined to return a single entity. No problems occur when a primitive type, a complex type or a collection of entities is returned. Assemblies affected
OData .Net lib 7.2 Reproduce steps
First define an entityset:
builder.EntitySet
("Entities"); Next define the collection-bound function:
builder.EntityType
().Collection .Function("MyFunction") .Returns (); And implement the function on the controller:
[HttpGet] public IHttpActionResult MyFunction() { return Ok(new MyEntity()); }Expected result
The invoked function should return an HTTP OK response with the correct data. Actual result
The following exception is thrown:
Exception thrown: 'Microsoft.OData.ODataException' in Microsoft.OData.Core.dll
When writing a JSON response, a user model must be specified and the entity set and entity type must be passed to the ODataMessageWriter.CreateODataResourceWriter method or the ODataResourceSerializationInfo must be set on the ODataResource or ODataResourceSet that is being written.
Partial stacktrace:
Microsoft.OData.Core.dll!Microsoft.OData.ODataResourceTypeContext.ValidateAndReturn
(string value) Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataResourceTypeContext.NavigationSourceName.get() Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataContextUrlInfo.Create(Microsoft.OData.ODataResourceTypeContext typeContext, bool isSingle, Microsoft.OData.ODataUri odataUri) Unknown Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightResourceSerializer.WriteResourceContextUri.AnonymousMethod__0() Unknown Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightSerializer.WriteContextUriProperty(Microsoft.OData.ODataPayloadKind payloadKind, System.Func<Microsoft.OData.ODataContextUrlInfo> contextUrlInfoGen, Microsoft.OData.ODataContextUrlInfo parentContextUrlInfo, string propertyName) Unknown Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightResourceSerializer.WriteResourceContextUri(Microsoft.OData.ODataResourceTypeContext typeContext, Microsoft.OData.ODataContextUrlInfo parentContextUrlInfo) Unknown Microsoft.OData.Core.dll!Microsoft.OData.JsonLight.ODataJsonLightWriter.StartResource(Microsoft.OData.ODataResource resource) Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStartResourceImplementation.AnonymousMethod__0() Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.InterceptException(System.Action action) Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStartResourceImplementation(Microsoft.OData.ODataResource resource) Unknown Microsoft.OData.Core.dll!Microsoft.OData.ODataWriterCore.WriteStart(Microsoft.OData.ODataResource resource) Unknown System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteResource(object graph, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext, Microsoft.OData.Edm.IEdmTypeReference expectedType) Unknown System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteObjectInline(object graph, Microsoft.OData.Edm.IEdmTypeReference expectedType, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Unknown ODataService.exe!RQuest.Web.OData.CustomODataResourceSerializer.WriteObjectInline(object graph, Microsoft.OData.Edm.IEdmTypeReference expectedType, Microsoft.OData.ODataWriter writer, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Line 78 C# System.Web.OData.dll!System.Web.OData.Formatter.Serialization.ODataResourceSerializer.WriteObject(object graph, System.Type type, Microsoft.OData.ODataMessageWriter messageWriter, System.Web.OData.Formatter.Serialization.ODataSerializerContext writeContext) Unknown System.Web.OData.dll!System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStream(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.Http.Headers.HttpContentHeaders contentHeaders) Unknown System.Web.OData.dll!System.Web.OData.Formatter.ODataMediaTypeFormatter.WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext, System.Threading.CancellationToken cancellationToken) Unknown System.Net.Http.Formatting.dll!System.Net.Http.Formatting.MediaTypeFormatter.WriteToStreamAsync(System.Type type, object value, System.IO.Stream writeStream, System.Net.Http.HttpContent content, System.Net.TransportContext transportContext) Unknown System.Net.Http.Formatting.dll!System.Net.Http.ObjectContent.SerializeToStreamAsync(System.IO.Stream stream, System.Net.TransportContext context) Unknown System.Net.Http.dll!System.Net.Http.HttpContent.LoadIntoBufferAsync(long maxBufferSize) Unknown System.Net.Http.dll!System.Net.Http.HttpContent.LoadIntoBufferAsync() Unknown System.Web.Http.Owin.dll!System.Web.Http.Owin.HttpMessageHandlerAdapter.BufferResponseContentAsync(System.Net.Http.HttpRequestMessage request, System.Net.Http.HttpResponseMessage response, System.Threading.CancellationToken cancellationToken) Unknown
Additional details
When the function returns a primitive type, a complex type or a collection of entities then all works fine. For example, the following works:
[HttpGet] public IHttpActionResult MyFunction() { return Ok(new MyEntity[] {MyEntity()}); }— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/OData/WebApi/issues/984, or mute the thread https://github.com/notifications/unsubscribe-auth/ABo2WYuOHu293wO5d8sZgnkZx4BZKcbWks5r_p_KgaJpZM4Ns2Mj .
Yes that fixed it, except I had to pass in the name of the collection:
ReturnsFromEntitySet<MyEntity>("MyEntities");
Out of curiousity, why such a complicated API? Couldn't the Returns<T> method handle this internally? After all, all the other types worked fine.
Let's have an example: ~/Customers(1)/Default.MyFunction(...)(2) , where, key 2 should know the entity set.
While 'Returns
Thanks your inputs and we'd love to see more contributions from you.
With the latest version of : Microsoft.OData.Client; if following this tutorial: https://docs.microsoft.com/en-us/dotnet/framework/data/wcf/querying-the-data-service-wcf-data-services I'm getting the same exception at the client side: When writing a JSON response, a user model must be specified
How can we force the usage ReturnsFromEntitySet in this case? Notes: I'm using VS2017 and added the Connected Service extension to generate the code for OdataV4 connection to a Microsoft NAV instance.
Hi, I am getting same error here i have specified as all steps mention. All working fine if i am executing from fiddler but when running from code with oData Client Code Generator it's giving error. here following is my setting.
ODataModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<CustomerLookup>("Customers");
builder.EntitySet<CustomerReachesVm>("CustomerReach");
builder.EntityType<CustomerReachesVm>().Property(x => x.ContactOrBusinessName).IsOptional();
builder.EntityType<CustomerReachesVm>().Property(x => x.PrimaryContactFirstName).IsOptional();
builder.EntityType<CustomerReachesVm>().Property(x => x.PrimaryContactLastName).IsOptional();
//builder.EntityType<CustomerReachesVm>().Property(x => x.CustomerStatus).IsOptional();
//builder.EntityType<CustomerReachesVm>().Property(x => x.CustomerType).IsOptional();
var customerReachConfiguration = builder.EntityType<CustomerReachesVm>()
.Collection
.Action("CallCenterCustomer")
//.ReturnsFromEntitySet<CustomerReachesVm>("CustomerReachesVm");
.ReturnsFromEntitySet<CustomerReachesVm>("CustomerReachesVm");
customerReachConfiguration.Parameter<int>("CompanyId");
customerReachConfiguration.Parameter<int>("CustomerId");
customerReachConfiguration.Parameter<string>("ContactName");
customerReachConfiguration.Parameter<string>("Address");
customerReachConfiguration.Parameter<string>("BusinessName");
customerReachConfiguration.Parameter<string>("FromDate");
customerReachConfiguration.Parameter<string>("ToDate");
builder.Namespace = "Default";
config.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
When writing a JSON response, a user model must be specified and the entity set and entity type must be passed to the ODataMessageWriter.CreateODataResourceWriter method or the ODataResourceSerializationInfo must be set on the ODataResource or ODataResourceSet that is being written.
Following is the call of oData.
Uri serviceUri = new Uri("http://aimm.acme.com/odata/CustomerReach/Default.CallCenterCustomer"); Container _context = new Container(serviceUri); string messageText = string.Empty; _context.SendingRequest2 += (objSender, objEventArgs) => { messageText = string.Format("{0} {1}", objEventArgs.RequestMessage.Method, objEventArgs.RequestMessage.Url); }; _context.BuildingRequest += (o, args) => args.Headers.Add("Authorization", "Bearer " + SecurityUtil.CurrentToken); _context.Format.UseJson();
BodyOperationParameter companyIdParam = new BodyOperationParameter("CompanyId", CurrentContext.CurrentContextCompanyId);
BodyOperationParameter customerIdParam = new BodyOperationParameter("CustomerId", searchCriteria.CustomerId);
BodyOperationParameter ContactNameParam = new BodyOperationParameter("ContactName", searchCriteria.ContactName);
BodyOperationParameter AddressParam = new BodyOperationParameter("Address", searchCriteria.Address);
BodyOperationParameter BusinessNameParam = new BodyOperationParameter("BusinessName", searchCriteria.BusinessName);
BodyOperationParameter FromDateParam = new BodyOperationParameter("FromDate", string.Empty);
BodyOperationParameter ToDateParam = new BodyOperationParameter("ToDate", string.Empty);
await this.RunWithWaitSpinnerAsync(async () =>
{
OperationParameter[] operationParameters = { companyIdParam, customerIdParam, ContactNameParam, AddressParam, BusinessNameParam, FromDateParam, ToDateParam };
var customerReachesVms = _context.Execute<Aimm.Client.BusinessLayer.ODataSupport.Aimm.Common.Model.CustomerReachesVm>(serviceUri, "POST", operationParameters);
// var customerReachesVms1 = _context.Execute<List<CustomerReachesVm>>(serviceUri, "POST", true, operationParameters);
foreach (var item in customerReachesVms)
{
// _customerReachesVms.Add(item);
}
});
Not sure where and why i am getting this error.