2017-08-02 36 views
-1

反序列化「的Guid」我想讀一個MongoDB的文件看起來像這樣無法從BsonType「的Int32」

{ 
"_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; } 
} 
+0

我已更新問題以回答您。 – nix86

+0

將Guid改爲字符串 – Koderzzzz

+0

@Koderzzzz幾乎所有東西都是JSON中的字符串,根本沒有任何幫助 –

回答

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; } 
0

我已經找到了解決辦法。問題是在文件中一個財產被拼錯了。所以C#代碼是正確的。問題出在MongoDB上。

相關問題