【发布时间】:2013-07-15 14:37:06
【问题描述】:
我正在使用 MongoDB 数据库和 MVC4 WebAPI,使用 MongoDB 提供的 C# 驱动程序。我有一个序列化问题。我收到以下错误,
"ExceptionMessage=Error getting value from '__emptyInstance' on 'MongoDB.Bson.ObjectId'"
如果我在我的 HTTP 请求中将 Content-Type 更改为 xml,它就可以正常工作。我将不胜感激。
我复制了下面的模型。
public class Subscriber
{
public ObjectId _id;
public long SubscriberId { get; set; }
public Name Name { get; set; }
public Address Address { get; set; }
public string Phone { get; set; }
public ICollection<Subscription> Subscription { get; set; }
public Subscriber()
{
Name = new Name();
Address = new Address();
Subscription = new Collection<Subscription>();
}
}
解决方案
转换 _id 类型字符串并如下所示装饰字段
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string _id;
【问题讨论】:
-
您能分享一下您尝试序列化为 JSON 的类型是什么样的吗?另外,从它说
MongoDB.Bson.ObjectId的错误来看,它应该是Bson格式化程序吗? Filip 在这里有一个创建 BSON 格式化程序的示例:gist.github.com/filipw/3160050 -
你能分享你的模型吗
-
我复制了上面的模型。问题是 ObjectId 没有被序列化。谢谢
标签: asp.net-web-api mongodb-.net-driver