1

I have a MongoDB helper class, which accepts generic types to simplify CRUD operations. I'm having some trouble figuring out the update method, however. From everything I've read, it seems that I need to individually update each field.

For example: Update.Set("Field", "New Value").Set("Other field", "Other value");

But what I'd like to do is something like this:

void Update(T entity)
{
    collection.Update<T>(entity);
}

Is this possible? Or will I need to include an update method in each entity's class specific to that entity?

Jedediah
  • 1,916
  • 16
  • 32

1 Answers1

2

Assuming that you want to update (replace) the entire object, do this:

void Update(T entity)
{
    collection.Save<T>(entity);
}

It will detect if the _id field is set and save the correct item.

If your object includes a primary key property (it should), you can decorate it with the attribute to give Mongo a hint

[BsonId()]

If you are looking at only updating certain fields, then you could always use reflection to loop through the properties of the type and add them to the Update's setters.

drz
  • 962
  • 7
  • 22