4

I have the following Model:

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

When I try to add a new UserInfo to database which has:

"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" as a key name in Metadata to my collection using:

Dbcontext.myCollection.InsertOne(data);

I get the following error message:

MongoDB.Bson.BsonSerializationException: 'Element name 'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name' is not valid'.'

I can tell that the issue is the dictionary having a url as a key, because when I removed this key from the dictionary, it worked fine, also when I used this value outside the dictionary it worked fine.

How can I overcome this issue?

Yahya Hussein
  • 8,767
  • 15
  • 58
  • 114
  • Have you tried other dictionary representations? https://stackoverflow.com/questions/28111846/bsonserializationexception-when-serializing-a-dictionarydatetime-t-to-bson – dnickless Jan 23 '18 at 15:45

1 Answers1

1

I'm not sure if you can serialize dictionaries directly into MongoDB but there is a work around it. You can convert dictionary to list of KeyValuePairs and it should work.

e.g.

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

and fill object to serialize into 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);

It should emit following document

{ 
  "_id" : ObjectId("5a678a3845acb9547c1ab4f9"), 
  "Metadata" : 
    [ 
      { "k" : "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "v" : "01" }
    ] 
}
Saleem
  • 8,728
  • 2
  • 20
  • 34
  • Well, the issue is not the dictionary itself, it is the value "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name" being a key in dictionary because when I removed this value from dictionary, everything got fine – Yahya Hussein Jan 24 '18 at 05:29