如何使用 MobogDB C# 驱动程序为实体编写自定义序列化程序?
How to write custom serializer for entity with MobogDB C# Driver?
我正在尝试从数据库中获取文档,但无法以理想的方式进行。
使用这种方法检索数据似乎很方便:
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();
我正在尝试从数据库中获取文档,但无法以理想的方式进行。 使用这种方法检索数据似乎很方便:
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();