Reputation: 2224
Following code from this question How to update a generic type with MongoDB C# driver no longer works, how to do the same in MongoDB 2.7?
void Update(T entity)
{
collection.Save<T>(entity);
}
Upvotes: 1
Views: 2138
Reputation: 49975
Currently Save
is only available in legacy MongoDB C# driver. You can find unresolved ticket with discussion on driver JIRA.
It's still possible to implement something similar in C#. The behavior is documented here:
If the document does not contain an _id field, then the save() method calls the insert() method. During the operation, the mongo shell will create an ObjectId and assign it to the _id field.
and
If the document contains an _id field, then the save() method is equivalent to an update with the upsert option set to true and the query predicate on the _id field.
So you can introduce marker interface in C# to represent _id
field:
public interface IIdentity
{
ObjectId Id { get; set; }
}
and then you can implement Save
like this:
public void Update<T>(T entity) where T : IIdentity
{
if(entity.Id == ObjectId.Empty)
{
collection.InsertOne(entity); // driver creates _id under the hood
}
else
{
collection.ReplaceOne(x => x.Id == entity.Id, entity, new UpdateOptions() { IsUpsert = true } );
}
}
or simpler:
public void Update<T>(T entity) where T : IIdentity
{
if(entity.Id == ObjectId.Empty)
{
entity.Id = ObjectId.GenerateNewId();
}
collection.ReplaceOne(x => x.Id == entity.Id, entity, new UpdateOptions() { IsUpsert = true } );
}
Upvotes: 2