OData / odata.net

ODataLib: Open Data Protocol - .NET Libraries and Frameworks
https://docs.microsoft.com/odata
Other
687 stars 349 forks source link

Aliasing/renaming properties on entities in OData #2099

Closed kevinlo closed 3 years ago

kevinlo commented 3 years ago

I need to have a entity model that has different property name from the OData one, I need to map them like using the JsonPropertyName.

I find this stackoverflow link and this ODataSamples page saying it can use the DataContract/DataMember like this:

[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;
}

I have tried using the DataMember attribute, but it does not work. The "Jack" is not mapped to the Bar.

I have spent some time to debug the OData.Client codes and find out the ClientTypeUtil.GetServerDefinedName function is checking the OriginalNameAttribute .

After I change the model to use OriginalName, it works.

public class Foo
{
    public Id { get; set;}

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

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

    public int Fizz { get; set; }

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

I check the OData documentation, it does not have any document talking about this.

My questions are:

  1. Is it the right way to use OriginalNameAttribute to do it?
  2. Is there any attribute like the NotMapped to tell that property should not be mapped? Is it the IgnoreClientPropertyAttribute?
  3. Can you add documentation about using the OriginalNameAttribute to do this mapping? I think some people may need it too as I have spent a day or more to find it out.

Thanks.

KenitoInc commented 3 years ago

Hey @kevinlo

  1. The OriginalNameAttribute is the right way to do it in OData client. As per the links you shared, we use DataContract/DataMember in OData WebApi.
  2. We don't have any at the moment.
  3. We will add the docs.