Do Azure table services entities have an equivalent of NonSerializedAttribute?

前端 未结 3 1378
囚心锁ツ
囚心锁ツ 2020-12-19 00:20

If I\'m trying to serialize a normal CLR object, and I do not want a particular member variable to be serialized, I can tag it with the

[NonSerialized]
         


        
3条回答
  •  独厮守ぢ
    2020-12-19 00:52

    For version 2.0 of the Table Storage SDK there is a new way to achieve this.

    You can now override the WriteEntity method on TableEntity and remove any entity properties that have an attribute on them. I derive from a class that does this for all my entities, like:

    public class CustomSerializationTableEntity : TableEntity
    {
        public CustomSerializationTableEntity()
        {
        }
    
        public CustomSerializationTableEntity(string partitionKey, string rowKey)
            : base(partitionKey, rowKey)
        {
        }
    
        public override IDictionary WriteEntity(Microsoft.WindowsAzure.Storage.OperationContext operationContext)
        {
            var entityProperties = base.WriteEntity(operationContext);
    
            var objectProperties = this.GetType().GetProperties();
    
            foreach (PropertyInfo property in objectProperties)
            {
                // see if the property has the attribute to not serialization, and if it does remove it from the entities to send to write
                object[] notSerializedAttributes = property.GetCustomAttributes(typeof(NotSerializedAttribute), false);
                if (notSerializedAttributes.Length > 0)
                {
                    entityProperties.Remove(property.Name);
                }
            }
    
            return entityProperties;
        }
    }
    
    [AttributeUsage(AttributeTargets.Property)]
    public class NotSerializedAttribute : Attribute
    {
    }
    

    Then you can make use of this class for your entities like

    public class MyEntity : CustomSerializationTableEntity
    {
         public MyEntity()
         {
         }
    
         public string MySerializedProperty { get; set; }
    
         [NotSerialized]
         public List MyNotSerializedProperty { get; set; }
    }
    

提交回复
热议问题