7
votes

Using the ODataConventionModelBuilder and its EntitySet<> functionality, is it possible to rename the names of properties on the entity sets?

Let's say I have an entity set type, Foo. It has two properties, Bar and Baz. However, in my OData model, I'd like the properties to instead to named Jack and Jane, respectively. Can I do this?

I was hoping for something like this:

var builder = new ODataConventionModelBuilder { Namespace = "Blah" };
var foo = builder.EntitySet<Foo>("Foo");
foo.AliasProperty(f => f.Bar, "Jack");
foo.AliasProperty(f => f.Baz, "Jane");

So far I've been unable to find something that does this.

2

2 Answers

4
votes

You can use the DataContract/DataMember to do this declaritively e.g.

[DataContract]
public class Foo
{
    [DataMember]
    public Id { get; set;}

    [DataMember(Name = "Jack"]
    public string Bar { get; set;}

    [DataMember(Name = "Jane"]
    public string Baz { get; set;}

    public int Fizz { get; set; }

    [NotMapped]
    public bool Buzz { get; set;
}

Anything without an attribute or with [NotMapped] will not be in the OData model.

Advantages

  • Can be used for any property type including navigation
  • Retains the class's property order in the metadata, changes in the
    ODataConventionModelBuilder happen before the model is built and so
    you tend to see your properties first

Disadvantages

  • Use of the NotMapped attribute can interfere with your database mapping, sometimes useful to use the convention that no attribute means it won't be in the OData model

This is also described in the official docs http://odata.github.io/WebApi/#02-04-convention-model-builder along with other attributes such as [ConcurrencyCheck] and [ComplexType]

4
votes

Yes, you can. Based on https://github.com/OData/ODataSamples/blob/master/WebApiClassic/ODataModelAliasingSample/ODataModelAliasingSample/Program.cs:

var builder = new ODataConventionModelBuilder { Namespace = "Blah" };
var foo = builder.EntitySet<Foo>("Foo");
foo.Property(f => f.Bar).Name = "Jack";
foo.Property(f => f.Baz).Name = "Jane";

I've been unable to use this for navigation properties though.