无法从BsonType'Int32'反序列化'Guid'

时间:2017-08-02 12:36:00

标签: c# mongodb guid

我正在尝试阅读看起来像这样的MongoDB文档

{
"_id":"a770cf8d-a2ec-45a0-8289-b312c6315997"
"foo1":"value of foo1",
"foo2":"value of foo2"
}

我正在使用C#驱动程序。问题是我收到以下错误:

Cannot deserialize a 'Guid' from BsonType 'Int32'.

我的C#代码如下所示:

var myCollection = myDatabase.GetCollection<MyType>(this.collectionName);
List<MyType> myThings = myCollection.Find(Builders<MyType>.Filter.Empty).ToList();

MyType如下所示:

[DataContract]
public class MyType
{
    [DataMember(Name="_id")]
    [BsonId(IdGenerator = typeof(CombGuidGenerator))]
    public Guid Id { get; set; }

    [DataMember(Name = "foo1")]
    [BsonElement("foo1")]
    public string Foo1{ get; set; }

    [DataMember(Name = "foo2")]
    [BsonElement("foo2")]
    public string Foo2{ get; set; }
}

2 个答案:

答案 0 :(得分:0)

我不知道BSON,但我怀疑问题是

[BsonId(IdGenerator = typeof(CombGuidGenerator))]
public Guid Id { get; set; }

看起来BsonId可能是Int32 ......但您将Id设置为GUID

也许这会有所帮助?

[BsonId(IdGenerator = typeof(BsonObjectIdGenerator))]
[NonSerialized]
public BsonObjectId _id;

或者:

[DataMember(Name="_id")]
[BsonId(IdGenerator = typeof(CombGuidGenerator))]
public int Id { get; set; }

答案 1 :(得分:0)

我找到了解决方案。问题是在文件中有一个属性被误解了。所以C#代码是正确的。问题出在MongoDB中。