【问题标题】:MongoDB throwing "MongoDB.Bson.BsonSerializationException" on InsertOneMongoDB 在 InsertOne 上抛出“MongoDB.Bson.BsonSerializationException”
【发布时间】:2018-01-23 14:35:59
【问题描述】:

我有以下型号:

Public class UserInfo{
 public string Id{get;}
 public   Dictionary<string, string> Metadata{ get; }
}

当我尝试将新的 UserInfo 添加到具有以下内容的数据库时:

"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" 作为 Metadata 中的键名使用:

Dbcontext.myCollection.InsertOne(data);

我收到以下错误消息:

MongoDB.Bson.BsonSerializationException: '元素名称 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name' 不是 有效'。'

我可以看出问题在于字典有一个 url 作为键,因为当我从字典中删除这个键时,它工作正常,当我在字典外使用这个值时它工作正常。

我该如何解决这个问题?

【问题讨论】:

标签: c# mongodb dictionary url serialization


【解决方案1】:

我不确定您是否可以将字典直接序列化到 MongoDB,但有一个解决方法。您可以将字典转换为 KeyValuePairs 列表,它应该可以工作。

例如

public class UserInfo
{
    [BsonId]
    public ObjectId Id { get; set; }
    public List<KeyValuePair<string, string>> Metadata { get; set; }
}

并填充对象以序列化到 MongoDB。

var userInfo = new UserInfo
{
    Metadata = new List<KeyValuePair<string, string>>()              
};

userInfo.Metadata.Add(new KeyValuePair<string, string>(
                          @"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "01"));

var userInfoCollection = mongoDatabase.GetCollection<UserInfo>("Users");
userInfoCollection.InsertOne(userInfo);

它应该发出以下文档

{ 
  "_id" : ObjectId("5a678a3845acb9547c1ab4f9"), 
  "Metadata" : 
    [ 
      { "k" : "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "v" : "01" }
    ] 
}

【讨论】:

猜你喜欢
  • 2018-02-03
  • 2019-02-04
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
  • 1970-01-01
相关资源
最近更新 更多