I made a partial class file to add new properties to my Entity-Framework generated model.
I am using WebAPI + OData, and the $metadata doesn't list my new/custom properties, and so the JSON it returns doesn't include my new/custom properties.
For example, let's say my Entity is "Person"
"Person" has one Database property; NumSpouses; an int which is returned in $metadata like this:
<Property Name="NumSpouses" Type="Edm.Int32"/>
That's great, but I added a property like this to a separate file, with a partial class:
public partial class Person {
...
public string MarriedStatus {
get { return this.NumSpouses==0 ? "Single" : "Married"; }
}
...
}
How can I get this Property available in my OData responses?
<Property Name="MarriedStatus" Type="Edm.String"/>
Currently, if I asked for MarriedStatus in $expand (as if it were a NavigationProperty.... which it's not [I thought I'd try $expand anyway as if it magically provided custom properties]), I'd get a message like this:
{
"odata.error":{
"code":"","message":{
"lang":"en-US","value":"The query specified in the URI is not valid. Could not find a property named 'MarriedStatus' on type 'fakeDataModels.Person'."
},"innererror":{
"message":"Could not find a property named 'MarriedStatus' on type 'fakeDataModels.Person'.","type":"Microsoft.Data.OData.ODataException","stacktrace":" at ..."
}
}
}
Controller.JsonJSON serialization is not the same as OData serialization, but I will point out that JSON will serialize theMarriedStatusproperty unless I explicitly say not to (ScriptIgnoreAttribute). Maybe this calls for the equivalent of a "ViewModel", I should add to my client-side (Javascript) code, which will just provide me the convenience functiongetMarriedStatus().ODataConventionModelBuilderand simply registering entity sets? Or something more sophisticated?ODataConventionModelBuilder builder = new ODataConventionModelBuilder(); builder.EntitySet<Person>("Person"); config.Routes.MapODataRoute("odata", "odata", builder.GetEdmModel());config.MapODataServiceRouterather thanconfig.Routes.MapODataRoute. Is your project OData V3 or V4?