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?
CodePudding user response:
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(),
...
}
CodePudding user response:
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.