如何用MobogDB c#驱动程序为实体编写自定义序列化器
本文关键字:自定义 序列化 实体 何用 MobogDB 驱动程序 | 更新日期: 2023-09-27 18:14:07
我试图从数据库中获取文档,但我不能以理想的方式做到这一点。使用这种方法检索数据似乎很方便:
var filter = Builders<Book>.Filter.Eq(x => x.Id == new ObjectId(id), true);
var result = await coll.Find(filter).ToListAsync();
但是在这种情况下,InvalidOperationException
在执行Find
方法时被抛出。除了文本:Unable to determine the serialization information for x => (x.Id == new ObjectId(value(BookService.Controllers.ImportController+<>c__DisplayClass1_0).id)).
public class Book
{
[BsonId]
public ObjectId Id { get; set; }
public string Author { get; set; }
public string Title { get; set; }
}
否则,当我使用这个过滤器:
var filter = Builders<Book>.Filter.Eq("_id", new ObjectId(id));
没有任何异常,结果包含适当的实体实例。似乎我需要实现自定义序列化器来确定当使用x.Id
时,它意味着通过_id
字段进行搜索,但我不知道如何做到这一点。或者也许有其他的方法来实现它?
代码不正确:
var filter = Builders<Book>.Filter.Eq(x => x.Id == new ObjectId(id), true);
改成这个应该能解决你的问题
var filter = Builders<Book>.Filter.Eq(x => x.Id, new ObjectId(id));
我总是在c#模型中将ObjectId表示为字符串,并使用BsonRepresentation作为属性来确保正确的序列化
[BsonRepresentation(BsonType.ObjectId)]
[BsonId]
public string Id { get; set; }
这样你的查询就像这样了:
var filter = Builders<Book>.Filter.Eq("_id", id);
var result = await coll.Find(filter).ToListAsync();
或者更好的
var result = await coll.Find(x => x.Id == id).ToListAsync();