So, here's the situation: I have a complex object that's coming from a database. And I have a second object (a list of objects, actually), that I want to APPEAR to the user to be something they can expand to, but are actually just runtime objects I have in the application..
So, what I'm trying to do is create a custom ODataResourceSerializer to append a model to data that's being serialized. I'm guessing I need to override AppendDynamicProperties, CreateStructuralProperty, CreateResource, or CreateSelectExpandNode, but I just don't know which one and how.
So in the image above, the normal EF/OData setup returns the left side when expanding to "RelatedPosts" b/c there aren't any in the DB, but I want to basically insert data there at serialization time.
Possible?
For some history, in overriding AppendDynamicProperties, I've been able to add a brand new property, as you can see in the screenshot above as "MyCustomProp". But I haven't figured out how to add an entire object. Here's the code for my class extending the ODataResourceSerializer
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.OData.Formatter.Serialization;
using Microsoft.OData;
using System.Web.OData;
using Microsoft.OData.Edm;
namespace Boomerang.OData
{
public class CustomODataResourceSerializer : ODataResourceSerializer
{
public CustomODataResourceSerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider)
{
}
public override Microsoft.OData.ODataProperty CreateStructuralProperty(IEdmStructuralProperty structuralProperty, ResourceContext resourceContext)
{
Microsoft.OData.ODataProperty property = base.CreateStructuralProperty(structuralProperty, resourceContext);
return property;
}
public override void AppendDynamicProperties(ODataResource resource, SelectExpandNode selectExpandNode, ResourceContext resourceContext)
{
// add property
var list = resource.Properties.ToList();
list.Add(new ODataProperty() { Name = "MyCustomProp", Value = "This Thing" });
resource.Properties = list.AsEnumerable();
base.AppendDynamicProperties(resource, selectExpandNode, resourceContext);
}
public override ODataResource CreateResource(SelectExpandNode selectExpandNode, ResourceContext resourceContext)
{
return base.CreateResource(selectExpandNode, resourceContext);
}
public override SelectExpandNode CreateSelectExpandNode(ResourceContext resourceContext)
{
return base.CreateSelectExpandNode(resourceContext);
}
public override void WriteObject(object graph, Type type, ODataMessageWriter messageWriter, ODataSerializerContext writeContext)
{
base.WriteObject(graph, type, messageWriter, writeContext);
}
}
}