如何使用MongoDB C#驱动程序更新泛型类型 [英] How to update a generic type with MongoDB C# driver
问题描述
我有一个MongoDB帮助程序类,该类接受通用类型以简化CRUD操作.但是,在确定更新方法时遇到了一些麻烦.从我阅读的所有内容来看,似乎我需要单独更新每个字段.
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.
例如: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);
}
这可能吗?还是我需要在特定于该实体的每个实体的类中包括一个update方法?
Is this possible? Or will I need to include an update method in each entity's class specific to that entity?
推荐答案
假定您要更新(替换)整个对象,请执行以下操作:
Assuming that you want to update (replace) the entire object, do this:
void Update(T entity)
{
collection.Save<T>(entity);
}
它将检测是否设置了_id字段并保存正确的项目.
It will detect if the _id field is set and save the correct item.
如果您的对象包含主键属性(应该),则可以使用该属性装饰对象,以向Mongo提示
If your object includes a primary key property (it should), you can decorate it with the attribute to give Mongo a hint
[BsonId()]
如果仅查看某些字段,则可以始终使用反射来遍历类型的属性,并将其添加到Update的设置器中.
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.
这篇关于如何使用MongoDB C#驱动程序更新泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!