skip to Main Content

I have this simple Object class, which is filled by json content of the api controller.

[BsonId] public string Id { get; }
[JsonIgnore] public string UserId { get; set; }

I want both of these variables to access the same GUID.

  1. Making guid static does not work as I want to create a new one on every object creation

  2. I tried using a constructor, but it seems not to be supported

     UserObject()
     {
     string guid = Guid.NewGuid().ToString();
     Id = guid;
     UserId = guid;
     }
    

How can this be accomplished?

2

Answers


  1. Firstly why do you need two duplicate fields?

    anyway…

    change object to:

        [BsonId]
        [BsonRepresentation(BsonType.String)]
        public Guid Id { get; set; }
    

    Mongo will store it as string but you can use GUID in code

    when you create object just use:

       new objectname(){
        Id = Guid.NewGuid(),
        ...
       }
    
    Login or Signup to reply.
  2. If you need both fields, you could "redirect" the UserId property to read and write the value of Id, e.g.:

    [BsonId] public string Id { get; }
    [JsonIgnore] public string UserId 
    { 
      get { return Id; }
      set { Id = value; }
    }
    

    When the JSON is deserialized in the controller, the Id property is set; as the UserId property uses the value of the Id property internally, the value of the properties is the same.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search