BsonIdAttribute.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. namespace MongoDB.Bson.Serialization.Attributes
  17. {
  18. /// <summary>
  19. /// Specifies that this is the Id field or property.
  20. /// </summary>
  21. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
  22. [BsonMemberMapAttributeUsage(AllowMultipleMembers = false)]
  23. public class BsonIdAttribute : Attribute, IBsonMemberMapAttribute
  24. {
  25. // private fields
  26. private Type _idGenerator;
  27. private int _order = int.MaxValue;
  28. // constructors
  29. /// <summary>
  30. /// Initializes a new instance of the BsonIdAttribute class.
  31. /// </summary>
  32. public BsonIdAttribute()
  33. {
  34. }
  35. // public properties
  36. /// <summary>
  37. /// Gets or sets the Id generator for the Id.
  38. /// </summary>
  39. public Type IdGenerator
  40. {
  41. get { return _idGenerator; }
  42. set { _idGenerator = value; }
  43. }
  44. /// <summary>
  45. /// Gets or sets the Id element serialization order.
  46. /// </summary>
  47. public int Order
  48. {
  49. get { return _order; }
  50. set { _order = value; }
  51. }
  52. // public methods
  53. /// <summary>
  54. /// Applies a modification to the member map.
  55. /// </summary>
  56. /// <param name="memberMap">The member map.</param>
  57. public void Apply(BsonMemberMap memberMap)
  58. {
  59. memberMap.SetOrder(_order);
  60. if (_idGenerator != null)
  61. {
  62. var idGenerator = (IIdGenerator)Activator.CreateInstance(_idGenerator); // public default constructor required
  63. memberMap.SetIdGenerator(idGenerator);
  64. }
  65. memberMap.ClassMap.SetIdMember(memberMap);
  66. }
  67. }
  68. }