Search code examples
c#odata

OData using ICollection<ITax> convert to strong type


I'm using OData to make a post, but I need to pass a strongly typed object, in my main class, I have this property that contains a collection of interfaces

public ICollection<ITax> Taxes { get; set; }

Each interface is implemented by a tax type, as we can see here.

    public sealed class Tax1 : ITax
    {
        public decimal BaseTotalAmount { get; set; }

        public decimal TotalAmount { get; set; }
    }

    public sealed class Tax2 : ITax
    {
        public decimal BaseTotalAmount { get; set; }

        public decimal TotalAmount { get; set; }
    }

The problem I'm not getting through via JSON that makes the identification of each type of tax.

"Taxes": [
        {
            "BaseTotalAmount": 1.0,
            "TotalAmount": 1.0
        }
    ]

how can I set a field that identifies me that the object is of type Tax1 in json?


Solution

  • There is an easy approach, that might not help you, but as you didn't deliver much of a context it is what I can give you.

    You just need one Tax class and in addition one enum. Let's say TaxType.

    public ICollection<Tax> Taxes { get; set; }
    
    public enum TaxType
    {
        TaxType1 = 0,
        TaxType2 = 1
    }
    
    public sealed class Tax : ITax
    {
        public TaxType Type { get; set; }
    
        public decimal BaseTotalAmount { get; set; }
    
        public decimal TotalAmount { get; set; }
    }
    

    Hope it helps