Quantcast
Channel: ASPNETWebStack Issue Tracker Rss Feed
Viewing all articles
Browse latest Browse all 7215

Edited Issue: Returning related entities when they are null. OData Web API [1134]

$
0
0
If I try to load a related entity which is null, for instance I have my schema as Carrier has many Phones and I retrieved a Phone and I want to load the Carrier but the Carrier is null (which is ok), then I go to my Container and do "LoadProperty(Phone, "Carrier")" I get an exception because on my Web API OData I have GetCarrier in my PhonesController and when it tries to return the Carrier from this Phone which is null it throws the following error:

```
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; odata=minimalmetadata; streaming=true; charset=utf-8'.
```

With an inner exception of:

```
Cannot serialize a null 'entry'.
```

And a stack trace:

```
at System.Web.Http.OData.Formatter.Serialization.ODataEntityTypeSerializer.WriteObject(Object graph, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
at System.Web.Http.OData.Formatter.ODataMediaTypeFormatter.<>c__DisplayClassa.<WriteToStreamAsync>b__9()
at System.Threading.Tasks.TaskHelpers.RunSynchronously(Action action, CancellationToken token)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Tracing.ITraceWriterExtensions.<TraceBeginEndAsyncCore>d__33.MoveNext()

```
Is this by design or should I be handling this differently?

My controller has the following method:

```
public Carrier GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

return phone.Carrier;
}
```

Or should I change my code to the following:

```
public HttpResponseMessage GetCarrier([FromODataUri] int key)
{
Phone phone = _context.Phones.Find(key);
if (phone == null)
{
throw ODataErrors.EntityNotFound(Request);
}

if(phone.Carrier == null)
return Request.CreateResponse(HttpStatusCode.OK);

return Request.CreateResponse(HttpStatusCode.OK, phone.Carrier);
}
```

By doing this I won't get the error anymore when trying to user LoadProperty even if the related entity is null. Is this the correct way of doing this?


Viewing all articles
Browse latest Browse all 7215

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>