Question

I have the following class.

public class User : System.Security.Principal.IPrincipal
{
    public int _id { get; set; }

    public IIdentity Identity { get; set; }

    public bool IsInRole(string role) { }    
}

I'm trying to save an instance of this class to a MongoDB using the following code:

new MongoClient("")
    .GetServer()
    .GetDatabase("")
    .GetCollection("")
        .Save<User>(
            new User 
            {
                _id = 101,
                Identity = new GenericIdentity("uName", "Custom")
            }
        );

After saving, when I retrieve the object from the DB; values of Identity.Name and Identity.AuthenticationType are still at null.

Is this due to a missing serialisation/de-serialization instructions?

I've tried with following Class Map but the problem remains the same.

BsonClassMap.RegisterClassMap<User>(cm =>
{
    cm.AutoMap();
    cm.MapIdProperty(c => c._id);
    cm.MapProperty(c => c.Identity);
});

EDIT

This is what get saved in the DB:

{
    "_id" : 101,
    "Identity" : {
        "_t" : "GenericIdentity",
        "Actor" : null,
        "BootstrapContext" : null,
        "Label" : null
    }
}
Was it helpful?

Solution

The problem is that GenericIdentity is not a data class and has a lot of properties that you don't want persisted. In this case, you're going to want to map this manually. Below, I'm going to map the only two properties that actually matter, the Name and the AuthenticationType. I'm then going to tell the MongoDB driver to construct a GenericIdentity using the constructor that takes these two parameters.

BsonClassMap.RegisterClassMap<GenericIdentity>(cm =>
{
    cm.MapProperty(c => c.Name);
    cm.MapProperty(c => c.AuthenticationType);
    cm.MapCreator(i => new GenericIdentity(i.Name, i.AuthenticationType));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top