I am trying to expose a read-only computed property through my OData v4 service using Web API. My searches only turn up posts from 2014 or older, with the only solutions being either obsolete code or the promise that computed properties would be supported in the next version of OData (I'm sure there have been a few "next versions" since then).
For my example, I'll use a Person
class with a combined FullName
:
public class Person
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
// My calculated property.
public string FullName
{
get
{
return FirstName + " " + LastName;
}
}
}
This is my WebAPIConfig
:
using System.Web.Http;
using System.Web.OData.Builder;
using System.Web.OData.Extensions;
using TestService.Models;
namespace TestService
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Person>("People");
config.MapODataServiceRoute("ODataRoute", null, builder.GetEdmModel());
}
}
}
At present, the JSON does not display the FullName
. What would it take to do that in the current version of everything?
Edit: Adding my controller for my Person
object:
using System.Web.Http;
using System.Web.OData;
using TestService.Models;
namespace TestService.Controllers
{
public class PeopleController : ODataController
{
DataContext db = new DataContext();
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
[EnableQuery]
public IQueryable<Person> Get()
{
return db.People;
}
[EnableQuery]
public SingleResult<Person> Get([FromODataUri] int key)
{
IQueryable<Person> result = db.People.Where(p => p.ID == key);
return SingleResult.Create(result);
}
}
}