Consider the following class
public class Something
{
public ObjectId Id;
public DateTime DbUpdatedAt;
public string AnotherProperty;
public int SomeIntProp;
}
I would normally do a partial update with the following code
var obj = ... // an instance of Something
var update = new UpdateBuilder<Something>();
update.Set(x => x.DbUpdatedAt, DateTime.UtcNow);
...
/// later on,
// database is an instance of MongoDatabase
database.GetCollection("CollectionName")
.Update(Query<Something>.Eq(x => x.Id, something.Id), update);
The problem is, I am not aware of any way to check whether update already has been configured to set a value for DbUpdatedAt.
If I blindly try to set a new value for DbUpdatedAt, I get an error.
...
/// later on,
update.Set(x => x.DbUpdatedAt, DateTime.UtcNow.AddHours(1)); // this throws a Duplicate element name error
// database is an instance of MongoDatabase
database.GetCollection("CollectionName")
.Update(Query<Something>.Eq(x => x.Id, something.Id), update);
I understand WHY the error happens. I need a way to,
- Detect there is a duplicate key scenario,
- Replace the old key,value pair with the new key,value pair.