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.
-
Making guid static does not work as I want to create a new one on every object creation
-
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
Firstly why do you need two duplicate fields?
anyway…
change object to:
Mongo will store it as string but you can use GUID in code
when you create object just use:
If you need both fields, you could "redirect" the
UserId
property to read and write the value ofId
, e.g.:When the JSON is deserialized in the controller, the
Id
property is set; as theUserId
property uses the value of theId
property internally, the value of the properties is the same.