@@ -13,9 +13,9 @@ public sealed class MetadataManager
1313 private class PropertyMetadata
1414 {
1515 public bool PresentInJson { get ; set ; } // only meaningful for incoming/deserialized models!
16- public Lazy < IEnumerable < System . Attribute > > AttributeOverrides
17- = new Lazy < IEnumerable < System . Attribute > > (
18- ( ) => new List < System . Attribute > ( )
16+ public Lazy < ISet < System . Attribute > > AttributeOverrides
17+ = new Lazy < ISet < System . Attribute > > (
18+ ( ) => new HashSet < System . Attribute > ( )
1919 ) ;
2020 }
2121
@@ -103,5 +103,46 @@ public bool PropertyWasPresent(object deserialized, PropertyInfo prop)
103103 return this . GetMetadataForProperty ( deserialized , prop ) . PresentInJson ;
104104 }
105105
106+ /// <summary>
107+ /// Set different serialization attributes at runtime than those that were declared on
108+ /// a property at compile time. E.g., if you declared a relationship property with
109+ /// [SerializeAs(SerializeAsOptions.Link)] but you want to change that to
110+ /// SerializeAsOptions.Ids when you are transmitting only one object, you can do:
111+ ///
112+ /// MetadataManager.SetPropertyAttributeOverrides(
113+ /// theModelInstance, theProperty,
114+ /// new SerializeAsAttribute(SerializeAsOptions.Ids)
115+ /// );
116+ ///
117+ /// Further, if you want to also include the related objects in the serialized document:
118+ ///
119+ /// MetadataManager.SetPropertyAttributeOverrides(
120+ /// theModelInstance, theProperty,
121+ /// new SerializeAs(SerializeAsOptions.Ids),
122+ /// new IncludeInPayload(true)
123+ /// );
124+ ///
125+ /// Calling this function resets all overrides, so calling it twice will result in only
126+ /// the second set of overrides being applied. At present, the order of the attributes
127+ /// is not meaningful.
128+ /// </summary>
129+ /// <param name="model">The model object that is to be serialized, for which you want to change serialization behavior.</param>
130+ /// <param name="prop">The property for which to override attributes.</param>
131+ /// <param name="attrs">One or more attribute instances that will override the declared behavior.</param>
132+ public void SetPropertyAttributeOverrides ( object model , PropertyInfo prop , params System . Attribute [ ] attrs )
133+ {
134+ var aoverrides = this . GetMetadataForProperty ( model , prop ) . AttributeOverrides . Value ;
135+ lock ( aoverrides )
136+ {
137+ aoverrides . Clear ( ) ;
138+ aoverrides . UnionWith ( attrs ) ;
139+ }
140+ }
141+
142+ internal IEnumerable < System . Attribute > GetPropertyAttributeOverrides ( object model , PropertyInfo prop )
143+ {
144+ return this . GetMetadataForProperty ( model , prop ) . AttributeOverrides . Value ;
145+ }
146+
106147 }
107148}
0 commit comments