Adding arbitrary data to OData metadata in WebAPI?

I have a simple WebAPI2 service that uses OData ( System.Web.Http.OData , 5.1.0.0). Users can press /odata/$metadata to get available objects and properties. I am looking for a way to extend this metadata to additional information, such as adding a display name value to a property.

I found โ€œannotationโ€ information that sounds like I want to, but I canโ€™t find anything explaining how to use this in my script or if possible. I tried to do something like the following:

 model.SetAnnotationValue(((IEdmEntityType)m.FindType("My.Thing")).FindProperty("SomeProperty"), namespaceName:"MyNamespace", localName: "SomeLocalName", value: "THINGS"); 

The type / property names are correct and the call succeeds, but the OData EDMX document does not contain this annotation. Is there a way to post these annotations or otherwise do what I want?

Update :
Still on it. I considered ODataMediaTypeFormatters as a possible way to handle this. There is a sample ASP.NET project that shows how to add instance annotations to objects. Close, but not quite what I want, so now I'm trying to find a way to extend what the metadata document generates in a similar way.

+6
source share
2 answers

I figured out a way to do this. The code below adds the custom namespace prefix "myns", and then adds the annotation to the model property:

 const string namespaceName = "http://my.org/schema"; var type = "My.Domain.Person"; const string localName = "MyCustomAttribute"; // this registers a "myns" namespace on the model model.SetNamespacePrefixMappings(new [] { new KeyValuePair<string, string>("myns", namespaceName), }); // set a simple string as the value of the "MyCustomAttribute" annotation on the "RevisionDate" property var stringType = EdmCoreModel.Instance.GetString(true); var value = new EdmStringConstant(stringType, "BUTTONS!!!"); m.SetAnnotationValue(((IEdmEntityType) m.FindType(type)).FindProperty("RevisionDate"), namespaceName, localName, value); 

An OData metadata document query should give you something like this:

 <edmx:Edmx Version="1.0"> <edmx:DataServices m:DataServiceVersion="3.0" m:MaxDataServiceVersion="3.0"> <Schema Namespace="My.Domain"> <EntityType Name="Person"> <Key><PropertyRef Name="PersonId"/></Key> <Property Name="RevisionDate" Type="Edm.Int32" Nullable="false" myns:MyCustomAttribute="BUTTONS!!!"/> </Schema> </edmx:DataServices> </edmx:Edmx> 
+10
source

You can set a custom property for any IEdmEntityType this way as well. Just change the kenchilada code as follows:

 m.SetAnnotationValue(m.FindType(type), namespaceName, localName, value); 
-1
source

All Articles