UserControl
UserControl

Reputation: 15159

How to make TableEntity serialize non-public properties?

Azure Table Storage has some frustrating limitations like inability to handle decimal data type so I have to do this:

public class MyEntity : TableEntity {
        [IgnoreProperty]
        public decimal ListPrice
        {
            get => decimal.Parse(this.ListPrice_, CultureInfo.InvariantCulture);
            set => this.ListPrice_ = value.ToString(CultureInfo.InvariantCulture);
        }

        public string ListPrice_ { get; set; }
}

Obviously I don't want ListPrice_ to be public but private members are seem to be ignored by the SDK. Is there any easy trick to make it serialize non-public members (without reflection)?

Upvotes: 0

Views: 1260

Answers (1)

Zhaoxing Lu
Zhaoxing Lu

Reputation: 6467

I don't know of any attribute that can be used to serialize a non-public property of TableEntity, but you can override ReadEntity and WriteEntity methods of interface ITableEntity to customize your own property serialization.

public class MyEntity : TableEntity
{
    [IgnoreProperty]
    public decimal ListPrice
    {
        get => decimal.Parse(this.ListPrice_, CultureInfo.InvariantCulture);
        set => this.ListPrice_ = value.ToString(CultureInfo.InvariantCulture);
    }

    private string ListPrice_ { get; set; }

    public override void ReadEntity(IDictionary<string, EntityProperty> properties, OperationContext operationContext)
    {
        this.ListPrice_ = properties[nameof(ListPrice)].StringValue;
    }

    public override IDictionary<string, EntityProperty> WriteEntity(OperationContext operationContext)
    {
        var properties = new Dictionary<string, EntityProperty>();
        properties.Add(nameof(ListPrice), new EntityProperty(this.ListPrice_));
        return properties;
    }
}

Upvotes: 2

Related Questions